]> granicus.if.org Git - clang/blob - Sema/SemaExpr.cpp
a82d0ad7e548ba223b295c322e5e92f1040e4b64
[clang] / Sema / SemaExpr.cpp
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Sema.h"
15 #include "SemaUtil.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/Parse/DeclSpec.h" 
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 using namespace clang;
27
28 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
29 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
30 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31 /// multiple tokens.  However, the common case is that StringToks points to one
32 /// string.
33 /// 
34 Action::ExprResult
35 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
36   assert(NumStringToks && "Must have at least one string!");
37
38   StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39   if (Literal.hadError)
40     return ExprResult(true);
41
42   llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43   for (unsigned i = 0; i != NumStringToks; ++i)
44     StringTokLocs.push_back(StringToks[i].getLocation());
45
46   // Verify that pascal strings aren't too large.
47   if (Literal.Pascal && Literal.GetStringLength() > 256)
48     return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
49                 SourceRange(StringToks[0].getLocation(),
50                             StringToks[NumStringToks-1].getLocation()));
51   
52   QualType StrTy = Context.CharTy;
53   // FIXME: handle wchar_t
54   if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
55   
56   // Get an array type for the string, according to C99 6.4.5.  This includes
57   // the nul terminator character as well as the string length for pascal
58   // strings.
59   StrTy = Context.getConstantArrayType(StrTy,
60                                    llvm::APInt(32, Literal.GetStringLength()+1),
61                                        ArrayType::Normal, 0);
62   
63   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
64   return new StringLiteral(Literal.GetString(), Literal.GetStringLength(), 
65                            Literal.AnyWide, StrTy, 
66                            StringToks[0].getLocation(),
67                            StringToks[NumStringToks-1].getLocation());
68 }
69
70
71 /// ActOnIdentifierExpr - The parser read an identifier in expression context,
72 /// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
73 /// identifier is used in an function call context.
74 Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
75                                            IdentifierInfo &II,
76                                            bool HasTrailingLParen) {
77   // Could be enum-constant or decl.
78   ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
79   if (D == 0) {
80     // Otherwise, this could be an implicitly declared function reference (legal
81     // in C90, extension in C99).
82     if (HasTrailingLParen &&
83         // Not in C++.
84         !getLangOptions().CPlusPlus)
85       D = ImplicitlyDefineFunction(Loc, II, S);
86     else {
87       if (CurMethodDecl) {
88         ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
89         ObjCInterfaceDecl *clsDeclared;
90         if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
91           IdentifierInfo &II = Context.Idents.get("self");
92           ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
93           return new ObjCIvarRefExpr(IV, IV->getType(), Loc, 
94                        static_cast<Expr*>(SelfExpr.Val), true, true);
95         }
96       }
97       // If this name wasn't predeclared and if this is not a function call,
98       // diagnose the problem.
99       return Diag(Loc, diag::err_undeclared_var_use, II.getName());
100     }
101   }
102   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
103     // check if referencing an identifier with __attribute__((deprecated)).
104     if (VD->getAttr<DeprecatedAttr>())
105       Diag(Loc, diag::warn_deprecated, VD->getName());
106
107     // Only create DeclRefExpr's for valid Decl's.
108     if (VD->isInvalidDecl())
109       return true;
110     return new DeclRefExpr(VD, VD->getType(), Loc);
111   }
112   if (isa<TypedefDecl>(D))
113     return Diag(Loc, diag::err_unexpected_typedef, II.getName());
114   if (isa<ObjCInterfaceDecl>(D))
115     return Diag(Loc, diag::err_unexpected_interface, II.getName());
116
117   assert(0 && "Invalid decl");
118   abort();
119 }
120
121 Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
122                                            tok::TokenKind Kind) {
123   PreDefinedExpr::IdentType IT;
124   
125   switch (Kind) {
126   default: assert(0 && "Unknown simple primary expr!");
127   case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
128   case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
129   case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
130   }
131
132   // Verify that this is in a function context.
133   if (CurFunctionDecl == 0 && CurMethodDecl == 0)
134     return Diag(Loc, diag::err_predef_outside_function);
135   
136   // Pre-defined identifiers are of type char[x], where x is the length of the
137   // string.
138   unsigned Length;
139   if (CurFunctionDecl)
140     Length = CurFunctionDecl->getIdentifier()->getLength();
141   else
142     Length = CurMethodDecl->getSynthesizedMethodSize();
143   
144   llvm::APInt LengthI(32, Length + 1);
145   QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
146   ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
147   return new PreDefinedExpr(Loc, ResTy, IT);
148 }
149
150 Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
151   llvm::SmallString<16> CharBuffer;
152   CharBuffer.resize(Tok.getLength());
153   const char *ThisTokBegin = &CharBuffer[0];
154   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
155   
156   CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
157                             Tok.getLocation(), PP);
158   if (Literal.hadError())
159     return ExprResult(true);
160   return new CharacterLiteral(Literal.getValue(), Context.IntTy, 
161                               Tok.getLocation());
162 }
163
164 Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
165   // fast path for a single digit (which is quite common). A single digit 
166   // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
167   if (Tok.getLength() == 1) {
168     const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
169     
170     unsigned IntSize = static_cast<unsigned>(
171       Context.getTypeSize(Context.IntTy, Tok.getLocation()));
172     return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
173                                          Context.IntTy, 
174                                          Tok.getLocation()));
175   }
176   llvm::SmallString<512> IntegerBuffer;
177   IntegerBuffer.resize(Tok.getLength());
178   const char *ThisTokBegin = &IntegerBuffer[0];
179   
180   // Get the spelling of the token, which eliminates trigraphs, etc.
181   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
182   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 
183                                Tok.getLocation(), PP);
184   if (Literal.hadError)
185     return ExprResult(true);
186   
187   Expr *Res;
188   
189   if (Literal.isFloatingLiteral()) {
190     QualType Ty;
191     const llvm::fltSemantics *Format;
192     uint64_t Size; unsigned Align;
193
194     if (Literal.isFloat) {
195       Ty = Context.FloatTy;
196       Context.Target.getFloatInfo(Size, Align, Format,
197                                   Context.getFullLoc(Tok.getLocation()));
198       
199     } else if (Literal.isLong) {
200       Ty = Context.LongDoubleTy;
201       Context.Target.getLongDoubleInfo(Size, Align, Format,
202                                        Context.getFullLoc(Tok.getLocation()));
203     } else {
204       Ty = Context.DoubleTy;
205       Context.Target.getDoubleInfo(Size, Align, Format,
206                                    Context.getFullLoc(Tok.getLocation()));
207     }
208     
209     // isExact will be set by GetFloatValue().
210     bool isExact = false;
211     
212     Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact, 
213                               Ty, Tok.getLocation());
214     
215   } else if (!Literal.isIntegerLiteral()) {
216     return ExprResult(true);
217   } else {
218     QualType t;
219
220     // long long is a C99 feature.
221     if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
222         Literal.isLongLong)
223       Diag(Tok.getLocation(), diag::ext_longlong);
224
225     // Get the value in the widest-possible width.
226     llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
227                             Context.getFullLoc(Tok.getLocation())), 0);
228    
229     if (Literal.GetIntegerValue(ResultVal)) {
230       // If this value didn't fit into uintmax_t, warn and force to ull.
231       Diag(Tok.getLocation(), diag::warn_integer_too_large);
232       t = Context.UnsignedLongLongTy;
233       assert(Context.getTypeSize(t, Tok.getLocation()) == 
234              ResultVal.getBitWidth() && "long long is not intmax_t?");
235     } else {
236       // If this value fits into a ULL, try to figure out what else it fits into
237       // according to the rules of C99 6.4.4.1p5.
238       
239       // Octal, Hexadecimal, and integers with a U suffix are allowed to
240       // be an unsigned int.
241       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
242
243       // Check from smallest to largest, picking the smallest type we can.
244       if (!Literal.isLong && !Literal.isLongLong) {
245         // Are int/unsigned possibilities?
246         unsigned IntSize = static_cast<unsigned>(
247           Context.getTypeSize(Context.IntTy,Tok.getLocation()));
248         // Does it fit in a unsigned int?
249         if (ResultVal.isIntN(IntSize)) {
250           // Does it fit in a signed int?
251           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
252             t = Context.IntTy;
253           else if (AllowUnsigned)
254             t = Context.UnsignedIntTy;
255         }
256         
257         if (!t.isNull())
258           ResultVal.trunc(IntSize);
259       }
260       
261       // Are long/unsigned long possibilities?
262       if (t.isNull() && !Literal.isLongLong) {
263         unsigned LongSize = static_cast<unsigned>(
264           Context.getTypeSize(Context.LongTy, Tok.getLocation()));
265      
266         // Does it fit in a unsigned long?
267         if (ResultVal.isIntN(LongSize)) {
268           // Does it fit in a signed long?
269           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
270             t = Context.LongTy;
271           else if (AllowUnsigned)
272             t = Context.UnsignedLongTy;
273         }
274         if (!t.isNull())
275           ResultVal.trunc(LongSize);
276       }      
277       
278       // Finally, check long long if needed.
279       if (t.isNull()) {
280         unsigned LongLongSize = static_cast<unsigned>(
281           Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
282         
283         // Does it fit in a unsigned long long?
284         if (ResultVal.isIntN(LongLongSize)) {
285           // Does it fit in a signed long long?
286           if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
287             t = Context.LongLongTy;
288           else if (AllowUnsigned)
289             t = Context.UnsignedLongLongTy;
290         }
291       }
292       
293       // If we still couldn't decide a type, we probably have something that
294       // does not fit in a signed long long, but has no U suffix.
295       if (t.isNull()) {
296         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
297         t = Context.UnsignedLongLongTy;
298       }
299     }
300
301     Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
302   }
303   
304   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
305   if (Literal.isImaginary)
306     Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
307   
308   return Res;
309 }
310
311 Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
312                                         ExprTy *Val) {
313   Expr *e = (Expr *)Val;
314   assert((e != 0) && "ActOnParenExpr() missing expr");
315   return new ParenExpr(L, R, e);
316 }
317
318 /// The UsualUnaryConversions() function is *not* called by this routine.
319 /// See C99 6.3.2.1p[2-4] for more details.
320 QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType, 
321                                          SourceLocation OpLoc, bool isSizeof) {
322   // C99 6.5.3.4p1:
323   if (isa<FunctionType>(exprType) && isSizeof)
324     // alignof(function) is allowed.
325     Diag(OpLoc, diag::ext_sizeof_function_type);
326   else if (exprType->isVoidType())
327     Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
328   else if (exprType->isIncompleteType()) {
329     Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type : 
330                            diag::err_alignof_incomplete_type,
331          exprType.getAsString());
332     return QualType(); // error
333   }
334   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
335   return Context.getSizeType();
336 }
337
338 Action::ExprResult Sema::
339 ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof, 
340                            SourceLocation LPLoc, TypeTy *Ty,
341                            SourceLocation RPLoc) {
342   // If error parsing type, ignore.
343   if (Ty == 0) return true;
344   
345   // Verify that this is a valid expression.
346   QualType ArgTy = QualType::getFromOpaquePtr(Ty);
347   
348   QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
349
350   if (resultType.isNull())
351     return true;
352   return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
353 }
354
355 QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
356   DefaultFunctionArrayConversion(V);
357   
358   // These operators return the element type of a complex type.
359   if (const ComplexType *CT = V->getType()->getAsComplexType())
360     return CT->getElementType();
361   
362   // Otherwise they pass through real integer and floating point types here.
363   if (V->getType()->isArithmeticType())
364     return V->getType();
365   
366   // Reject anything else.
367   Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
368   return QualType();
369 }
370
371
372
373 Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc, 
374                                              tok::TokenKind Kind,
375                                              ExprTy *Input) {
376   UnaryOperator::Opcode Opc;
377   switch (Kind) {
378   default: assert(0 && "Unknown unary op!");
379   case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
380   case tok::minusminus: Opc = UnaryOperator::PostDec; break;
381   }
382   QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
383   if (result.isNull())
384     return true;
385   return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
386 }
387
388 Action::ExprResult Sema::
389 ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
390                         ExprTy *Idx, SourceLocation RLoc) {
391   Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
392
393   // Perform default conversions.
394   DefaultFunctionArrayConversion(LHSExp);
395   DefaultFunctionArrayConversion(RHSExp);
396   
397   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
398
399   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
400   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
401   // in the subscript position. As a result, we need to derive the array base 
402   // and index from the expression types.
403   Expr *BaseExpr, *IndexExpr;
404   QualType ResultType;
405   if (const PointerType *PTy = LHSTy->getAsPointerType()) {
406     BaseExpr = LHSExp;
407     IndexExpr = RHSExp;
408     // FIXME: need to deal with const...
409     ResultType = PTy->getPointeeType();
410   } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
411      // Handle the uncommon case of "123[Ptr]".
412     BaseExpr = RHSExp;
413     IndexExpr = LHSExp;
414     // FIXME: need to deal with const...
415     ResultType = PTy->getPointeeType();
416   } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
417     BaseExpr = LHSExp;    // vectors: V[123]
418     IndexExpr = RHSExp;
419     
420     // Component access limited to variables (reject vec4.rg[1]).
421     if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr)) 
422       return Diag(LLoc, diag::err_ocuvector_component_access, 
423                   SourceRange(LLoc, RLoc));
424     // FIXME: need to deal with const...
425     ResultType = VTy->getElementType();
426   } else {
427     return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value, 
428                 RHSExp->getSourceRange());
429   }              
430   // C99 6.5.2.1p1
431   if (!IndexExpr->getType()->isIntegerType())
432     return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
433                 IndexExpr->getSourceRange());
434
435   // C99 6.5.2.1p1: "shall have type "pointer to *object* type".  In practice,
436   // the following check catches trying to index a pointer to a function (e.g.
437   // void (*)(int)). Functions are not objects in C99.
438   if (!ResultType->isObjectType())
439     return Diag(BaseExpr->getLocStart(), 
440                 diag::err_typecheck_subscript_not_object,
441                 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
442
443   return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
444 }
445
446 QualType Sema::
447 CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
448                         IdentifierInfo &CompName, SourceLocation CompLoc) {
449   const OCUVectorType *vecType = baseType->getAsOCUVectorType();
450   
451   // The vector accessor can't exceed the number of elements.
452   const char *compStr = CompName.getName();
453   if (strlen(compStr) > vecType->getNumElements()) {
454     Diag(OpLoc, diag::err_ocuvector_component_exceeds_length, 
455                 baseType.getAsString(), SourceRange(CompLoc));
456     return QualType();
457   }
458   // The component names must come from the same set.
459   if (vecType->getPointAccessorIdx(*compStr) != -1) {
460     do
461       compStr++;
462     while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
463   } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
464     do
465       compStr++;
466     while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
467   } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
468     do 
469       compStr++;
470     while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
471   }
472     
473   if (*compStr) { 
474     // We didn't get to the end of the string. This means the component names
475     // didn't come from the same set *or* we encountered an illegal name.
476     Diag(OpLoc, diag::err_ocuvector_component_name_illegal, 
477          std::string(compStr,compStr+1), SourceRange(CompLoc));
478     return QualType();
479   }
480   // Each component accessor can't exceed the vector type.
481   compStr = CompName.getName();
482   while (*compStr) {
483     if (vecType->isAccessorWithinNumElements(*compStr))
484       compStr++;
485     else
486       break;
487   }
488   if (*compStr) { 
489     // We didn't get to the end of the string. This means a component accessor
490     // exceeds the number of elements in the vector.
491     Diag(OpLoc, diag::err_ocuvector_component_exceeds_length, 
492                 baseType.getAsString(), SourceRange(CompLoc));
493     return QualType();
494   }
495   // The component accessor looks fine - now we need to compute the actual type.
496   // The vector type is implied by the component accessor. For example, 
497   // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
498   unsigned CompSize = strlen(CompName.getName());
499   if (CompSize == 1)
500     return vecType->getElementType();
501     
502   QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
503   // Now look up the TypeDefDecl from the vector type. Without this, 
504   // diagostics look bad. We want OCU vector types to appear built-in.
505   for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
506     if (OCUVectorDecls[i]->getUnderlyingType() == VT)
507       return Context.getTypedefType(OCUVectorDecls[i]);
508   }
509   return VT; // should never get here (a typedef type should always be found).
510 }
511
512 Action::ExprResult Sema::
513 ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
514                          tok::TokenKind OpKind, SourceLocation MemberLoc,
515                          IdentifierInfo &Member) {
516   Expr *BaseExpr = static_cast<Expr *>(Base);
517   assert(BaseExpr && "no record expression");
518
519   // Perform default conversions.
520   DefaultFunctionArrayConversion(BaseExpr);
521   
522   QualType BaseType = BaseExpr->getType();
523   assert(!BaseType.isNull() && "no type for member expression");
524   
525   if (OpKind == tok::arrow) {
526     if (const PointerType *PT = BaseType->getAsPointerType())
527       BaseType = PT->getPointeeType();
528     else
529       return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
530                   SourceRange(MemberLoc));
531   }
532   // The base type is either a record or an OCUVectorType.
533   if (const RecordType *RTy = BaseType->getAsRecordType()) {
534     RecordDecl *RDecl = RTy->getDecl();
535     if (RTy->isIncompleteType())
536       return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
537                   BaseExpr->getSourceRange());
538     // The record definition is complete, now make sure the member is valid.
539     FieldDecl *MemberDecl = RDecl->getMember(&Member);
540     if (!MemberDecl)
541       return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
542                   SourceRange(MemberLoc));
543
544     // Figure out the type of the member; see C99 6.5.2.3p3
545     // FIXME: Handle address space modifiers
546     QualType MemberType = MemberDecl->getType();
547     unsigned combinedQualifiers =
548         MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
549     MemberType = MemberType.getQualifiedType(combinedQualifiers);
550
551     return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
552                           MemberLoc, MemberType);
553   } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
554     // Component access limited to variables (reject vec4.rg.g).
555     if (!isa<DeclRefExpr>(BaseExpr)) 
556       return Diag(OpLoc, diag::err_ocuvector_component_access, 
557                   SourceRange(MemberLoc));
558     QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
559     if (ret.isNull())
560       return true;
561     return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
562   } else if (BaseType->isObjCInterfaceType()) {
563     ObjCInterfaceDecl *IFace;
564     if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
565       IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
566     else
567       IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
568     ObjCInterfaceDecl *clsDeclared;
569     if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
570       return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr, 
571                                  OpKind==tok::arrow);
572   }
573   return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
574               SourceRange(MemberLoc));
575 }
576
577 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
578 /// This provides the location of the left/right parens and a list of comma
579 /// locations.
580 Action::ExprResult Sema::
581 ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
582               ExprTy **args, unsigned NumArgs,
583               SourceLocation *CommaLocs, SourceLocation RParenLoc) {
584   Expr *Fn = static_cast<Expr *>(fn);
585   Expr **Args = reinterpret_cast<Expr**>(args);
586   assert(Fn && "no function call expression");
587   
588   // Make the call expr early, before semantic checks.  This guarantees cleanup
589   // of arguments and function on error.
590   llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
591                                                  Context.BoolTy, RParenLoc));
592   
593   // Promote the function operand.
594   TheCall->setCallee(UsualUnaryConversions(Fn));
595   
596   // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
597   // type pointer to function".
598   const PointerType *PT = Fn->getType()->getAsPointerType();
599   if (PT == 0)
600     return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
601                 SourceRange(Fn->getLocStart(), RParenLoc));
602   const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
603   if (FuncT == 0)
604     return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
605                 SourceRange(Fn->getLocStart(), RParenLoc));
606   
607   // We know the result type of the call, set it.
608   TheCall->setType(FuncT->getResultType());
609     
610   if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
611     // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 
612     // assignment, to the types of the corresponding parameter, ...
613     unsigned NumArgsInProto = Proto->getNumArgs();
614     unsigned NumArgsToCheck = NumArgs;
615     
616     // If too few arguments are available, don't make the call.
617     if (NumArgs < NumArgsInProto)
618       return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
619                   Fn->getSourceRange());
620     
621     // If too many are passed and not variadic, error on the extras and drop
622     // them.
623     if (NumArgs > NumArgsInProto) {
624       if (!Proto->isVariadic()) {
625         Diag(Args[NumArgsInProto]->getLocStart(), 
626              diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
627              SourceRange(Args[NumArgsInProto]->getLocStart(),
628                          Args[NumArgs-1]->getLocEnd()));
629         // This deletes the extra arguments.
630         TheCall->setNumArgs(NumArgsInProto);
631       }
632       NumArgsToCheck = NumArgsInProto;
633     }
634     
635     // Continue to check argument types (even if we have too few/many args).
636     for (unsigned i = 0; i != NumArgsToCheck; i++) {
637       Expr *Arg = Args[i];
638       QualType ProtoArgType = Proto->getArgType(i);
639       QualType ArgType = Arg->getType();
640
641       // Compute implicit casts from the operand to the formal argument type.
642       AssignConvertType ConvTy =
643         CheckSingleAssignmentConstraints(ProtoArgType, Arg);
644       TheCall->setArg(i, Arg);
645       
646       if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
647                                    ArgType, Arg, "passing"))
648         return true;
649     }
650     
651     // If this is a variadic call, handle args passed through "...".
652     if (Proto->isVariadic()) {
653       // Promote the arguments (C99 6.5.2.2p7).
654       for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
655         Expr *Arg = Args[i];
656         DefaultArgumentPromotion(Arg);
657         TheCall->setArg(i, Arg);
658       }
659     }
660   } else {
661     assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
662     
663     // Promote the arguments (C99 6.5.2.2p6).
664     for (unsigned i = 0; i != NumArgs; i++) {
665       Expr *Arg = Args[i];
666       DefaultArgumentPromotion(Arg);
667       TheCall->setArg(i, Arg);
668     }
669   }
670
671   // Do special checking on direct calls to functions.
672   if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
673     if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
674       if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
675         if (CheckFunctionCall(FDecl, TheCall.get()))
676           return true;
677
678   return TheCall.take();
679 }
680
681 Action::ExprResult Sema::
682 ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
683                      SourceLocation RParenLoc, ExprTy *InitExpr) {
684   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
685   QualType literalType = QualType::getFromOpaquePtr(Ty);
686   // FIXME: put back this assert when initializers are worked out.
687   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
688   Expr *literalExpr = static_cast<Expr*>(InitExpr);
689
690   // FIXME: add more semantic analysis (C99 6.5.2.5).
691   if (CheckInitializerTypes(literalExpr, literalType))
692     return true;
693
694   bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
695   if (isFileScope) { // 6.5.2.5p3
696     if (CheckForConstantInitializer(literalExpr, literalType))
697       return true;
698   }
699   return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
700 }
701
702 Action::ExprResult Sema::
703 ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
704               SourceLocation RBraceLoc) {
705   Expr **InitList = reinterpret_cast<Expr**>(initlist);
706
707   // Semantic analysis for initializers is done by ActOnDeclarator() and
708   // CheckInitializer() - it requires knowledge of the object being intialized. 
709   
710   InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
711   e->setType(Context.VoidTy); // FIXME: just a place holder for now.
712   return e;
713 }
714
715 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
716   assert(VectorTy->isVectorType() && "Not a vector type!");
717   
718   if (Ty->isVectorType() || Ty->isIntegerType()) {
719     if (Context.getTypeSize(VectorTy, SourceLocation()) !=
720         Context.getTypeSize(Ty, SourceLocation()))
721       return Diag(R.getBegin(),
722                   Ty->isVectorType() ? 
723                   diag::err_invalid_conversion_between_vectors :
724                   diag::err_invalid_conversion_between_vector_and_integer,
725                   VectorTy.getAsString().c_str(),
726                   Ty.getAsString().c_str(), R);
727   } else
728     return Diag(R.getBegin(),
729                 diag::err_invalid_conversion_between_vector_and_scalar,
730                 VectorTy.getAsString().c_str(),
731                 Ty.getAsString().c_str(), R);
732   
733   return false;
734 }
735
736 Action::ExprResult Sema::
737 ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
738               SourceLocation RParenLoc, ExprTy *Op) {
739   assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
740
741   Expr *castExpr = static_cast<Expr*>(Op);
742   QualType castType = QualType::getFromOpaquePtr(Ty);
743
744   UsualUnaryConversions(castExpr);
745
746   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
747   // type needs to be scalar.
748   if (!castType->isVoidType()) {  // Cast to void allows any expr type.
749     if (!castType->isScalarType() && !castType->isVectorType())
750       return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar, 
751                   castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
752     if (!castExpr->getType()->isScalarType() && 
753         !castExpr->getType()->isVectorType())
754       return Diag(castExpr->getLocStart(), 
755                   diag::err_typecheck_expect_scalar_operand, 
756                   castExpr->getType().getAsString(),castExpr->getSourceRange());
757
758     if (castExpr->getType()->isVectorType()) {
759       if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc), 
760                           castExpr->getType(), castType))
761         return true;
762     } else if (castType->isVectorType()) {
763       if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc), 
764                           castType, castExpr->getType()))
765         return true;
766     }
767   }
768   return new CastExpr(castType, castExpr, LParenLoc);
769 }
770
771 /// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
772 /// In that case, lex = cond.
773 inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
774   Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
775   UsualUnaryConversions(cond);
776   UsualUnaryConversions(lex);
777   UsualUnaryConversions(rex);
778   QualType condT = cond->getType();
779   QualType lexT = lex->getType();
780   QualType rexT = rex->getType();
781
782   // first, check the condition.
783   if (!condT->isScalarType()) { // C99 6.5.15p2
784     Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar, 
785          condT.getAsString());
786     return QualType();
787   }
788   
789   // Now check the two expressions.
790   
791   // If both operands have arithmetic type, do the usual arithmetic conversions
792   // to find a common type: C99 6.5.15p3,5.
793   if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
794     UsualArithmeticConversions(lex, rex);
795     return lex->getType();
796   }
797   
798   // If both operands are the same structure or union type, the result is that
799   // type.
800   if (const RecordType *LHSRT = lexT->getAsRecordType()) {    // C99 6.5.15p3
801     if (const RecordType *RHSRT = rexT->getAsRecordType())
802       if (LHSRT->getDecl() == RHSRT->getDecl())
803         // "If both the operands have structure or union type, the result has 
804         // that type."  This implies that CV qualifiers are dropped.
805         return lexT.getUnqualifiedType();
806   }
807   
808   // C99 6.5.15p5: "If both operands have void type, the result has void type."
809   if (lexT->isVoidType() && rexT->isVoidType())
810     return lexT.getUnqualifiedType();
811
812   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
813   // the type of the other operand."
814   if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
815     ImpCastExprToType(rex, lexT); // promote the null to a pointer.
816     return lexT;
817   }
818   if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
819     ImpCastExprToType(lex, rexT); // promote the null to a pointer.
820     return rexT;
821   }
822   // Handle the case where both operands are pointers before we handle null
823   // pointer constants in case both operands are null pointer constants.
824   if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
825     if (const PointerType *RHSPT = rexT->getAsPointerType()) {
826       // get the "pointed to" types
827       QualType lhptee = LHSPT->getPointeeType();
828       QualType rhptee = RHSPT->getPointeeType();
829
830       // ignore qualifiers on void (C99 6.5.15p3, clause 6)
831       if (lhptee->isVoidType() &&
832           (rhptee->isObjectType() || rhptee->isIncompleteType())) {
833         // Figure out necessary qualifiers (C99 6.5.15p6)
834         QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
835         QualType destType = Context.getPointerType(destPointee);
836         ImpCastExprToType(lex, destType); // add qualifiers if necessary
837         ImpCastExprToType(rex, destType); // promote to void*
838         return destType;
839       }
840       if (rhptee->isVoidType() &&
841           (lhptee->isObjectType() || lhptee->isIncompleteType())) {
842         QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
843         QualType destType = Context.getPointerType(destPointee);
844         ImpCastExprToType(lex, destType); // add qualifiers if necessary
845         ImpCastExprToType(rex, destType); // promote to void*
846         return destType;
847       }
848
849       if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 
850                                       rhptee.getUnqualifiedType())) {
851         Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
852              lexT.getAsString(), rexT.getAsString(),
853              lex->getSourceRange(), rex->getSourceRange());
854         // In this situation, we assume void* type. No especially good
855         // reason, but this is what gcc does, and we do have to pick
856         // to get a consistent AST.
857         QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
858         ImpCastExprToType(lex, voidPtrTy);
859         ImpCastExprToType(rex, voidPtrTy);
860         return voidPtrTy;
861       }
862       // The pointer types are compatible.
863       // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
864       // differently qualified versions of compatible types, the result type is
865       // a pointer to an appropriately qualified version of the *composite*
866       // type.
867       // FIXME: Need to return the composite type.
868       // FIXME: Need to add qualifiers
869       return lexT;
870     }
871   }
872   
873   // Otherwise, the operands are not compatible.
874   Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
875        lexT.getAsString(), rexT.getAsString(),
876        lex->getSourceRange(), rex->getSourceRange());
877   return QualType();
878 }
879
880 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
881 /// in the case of a the GNU conditional expr extension.
882 Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 
883                                             SourceLocation ColonLoc,
884                                             ExprTy *Cond, ExprTy *LHS,
885                                             ExprTy *RHS) {
886   Expr *CondExpr = (Expr *) Cond;
887   Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
888
889   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
890   // was the condition.
891   bool isLHSNull = LHSExpr == 0;
892   if (isLHSNull)
893     LHSExpr = CondExpr;
894   
895   QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 
896                                              RHSExpr, QuestionLoc);
897   if (result.isNull())
898     return true;
899   return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
900                                  RHSExpr, result);
901 }
902
903 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
904 /// do not have a prototype. Arguments that have type float are promoted to 
905 /// double. All other argument types are converted by UsualUnaryConversions().
906 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
907   QualType Ty = Expr->getType();
908   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
909
910   if (Ty == Context.FloatTy)
911     ImpCastExprToType(Expr, Context.DoubleTy);
912   else
913     UsualUnaryConversions(Expr);
914 }
915
916 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
917 void Sema::DefaultFunctionArrayConversion(Expr *&e) {
918   QualType t = e->getType();
919   assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
920
921   if (const ReferenceType *ref = t->getAsReferenceType()) {
922     ImpCastExprToType(e, ref->getReferenceeType()); // C++ [expr]
923     t = e->getType();
924   }
925   if (t->isFunctionType())
926     ImpCastExprToType(e, Context.getPointerType(t));
927   else if (const ArrayType *ary = t->getAsArrayType()) {
928     // Make sure we don't lose qualifiers when dealing with typedefs. Example:
929     //   typedef int arr[10];
930     //   void test2() {
931     //     const arr b;
932     //     b[4] = 1;
933     //   }
934     QualType ELT = ary->getElementType();
935     // FIXME: Handle ASQualType
936     ELT = ELT.getQualifiedType(t.getCVRQualifiers()|ELT.getCVRQualifiers());
937     ImpCastExprToType(e, Context.getPointerType(ELT));
938   }
939 }
940
941 /// UsualUnaryConversions - Performs various conversions that are common to most
942 /// operators (C99 6.3). The conversions of array and function types are 
943 /// sometimes surpressed. For example, the array->pointer conversion doesn't
944 /// apply if the array is an argument to the sizeof or address (&) operators.
945 /// In these instances, this routine should *not* be called.
946 Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
947   QualType Ty = Expr->getType();
948   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
949   
950   if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
951     ImpCastExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
952     Ty = Expr->getType();
953   }
954   if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
955     ImpCastExprToType(Expr, Context.IntTy);
956   else
957     DefaultFunctionArrayConversion(Expr);
958   
959   return Expr;
960 }
961
962 /// UsualArithmeticConversions - Performs various conversions that are common to
963 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
964 /// routine returns the first non-arithmetic type found. The client is 
965 /// responsible for emitting appropriate error diagnostics.
966 /// FIXME: verify the conversion rules for "complex int" are consistent with GCC.
967 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
968                                           bool isCompAssign) {
969   if (!isCompAssign) {
970     UsualUnaryConversions(lhsExpr);
971     UsualUnaryConversions(rhsExpr);
972   }
973   // For conversion purposes, we ignore any qualifiers. 
974   // For example, "const float" and "float" are equivalent.
975   QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
976   QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
977   
978   // If both types are identical, no conversion is needed.
979   if (lhs == rhs)
980     return lhs;
981   
982   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
983   // The caller can deal with this (e.g. pointer + int).
984   if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
985     return lhs;
986     
987   // At this point, we have two different arithmetic types. 
988   
989   // Handle complex types first (C99 6.3.1.8p1).
990   if (lhs->isComplexType() || rhs->isComplexType()) {
991     // if we have an integer operand, the result is the complex type.
992     if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 
993       // convert the rhs to the lhs complex type.
994       if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
995       return lhs;
996     }
997     if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 
998       // convert the lhs to the rhs complex type.
999       if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1000       return rhs;
1001     }
1002     // This handles complex/complex, complex/float, or float/complex.
1003     // When both operands are complex, the shorter operand is converted to the 
1004     // type of the longer, and that is the type of the result. This corresponds 
1005     // to what is done when combining two real floating-point operands. 
1006     // The fun begins when size promotion occur across type domains. 
1007     // From H&S 6.3.4: When one operand is complex and the other is a real
1008     // floating-point type, the less precise type is converted, within it's 
1009     // real or complex domain, to the precision of the other type. For example,
1010     // when combining a "long double" with a "double _Complex", the 
1011     // "double _Complex" is promoted to "long double _Complex".
1012     int result = Context.compareFloatingType(lhs, rhs);
1013     
1014     if (result > 0) { // The left side is bigger, convert rhs. 
1015       rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1016       if (!isCompAssign)
1017         ImpCastExprToType(rhsExpr, rhs);
1018     } else if (result < 0) { // The right side is bigger, convert lhs. 
1019       lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1020       if (!isCompAssign)
1021         ImpCastExprToType(lhsExpr, lhs);
1022     } 
1023     // At this point, lhs and rhs have the same rank/size. Now, make sure the
1024     // domains match. This is a requirement for our implementation, C99
1025     // does not require this promotion.
1026     if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1027       if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
1028         if (!isCompAssign)
1029           ImpCastExprToType(lhsExpr, rhs);
1030         return rhs;
1031       } else { // handle "_Complex double, double".
1032         if (!isCompAssign)
1033           ImpCastExprToType(rhsExpr, lhs);
1034         return lhs;
1035       }
1036     }
1037     return lhs; // The domain/size match exactly.
1038   }
1039   // Now handle "real" floating types (i.e. float, double, long double).
1040   if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1041     // if we have an integer operand, the result is the real floating type.
1042     if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 
1043       // convert rhs to the lhs floating point type.
1044       if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1045       return lhs;
1046     }
1047     if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 
1048       // convert lhs to the rhs floating point type.
1049       if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1050       return rhs;
1051     }
1052     // We have two real floating types, float/complex combos were handled above.
1053     // Convert the smaller operand to the bigger result.
1054     int result = Context.compareFloatingType(lhs, rhs);
1055     
1056     if (result > 0) { // convert the rhs
1057       if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1058       return lhs;
1059     }
1060     if (result < 0) { // convert the lhs
1061       if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
1062       return rhs;
1063     }
1064     assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
1065   }
1066   if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1067     // Handle GCC complex int extension.
1068     const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
1069     const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
1070
1071     if (lhsComplexInt && rhsComplexInt) {
1072       if (Context.maxIntegerType(lhsComplexInt->getElementType(), 
1073                                  rhsComplexInt->getElementType()) == lhs) {
1074         // convert the rhs
1075         if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1076         return lhs;
1077       }
1078       if (!isCompAssign) 
1079         ImpCastExprToType(lhsExpr, rhs); // convert the lhs
1080       return rhs;
1081     } else if (lhsComplexInt && rhs->isIntegerType()) {
1082       // convert the rhs to the lhs complex type.
1083       if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1084       return lhs;
1085     } else if (rhsComplexInt && lhs->isIntegerType()) {
1086       // convert the lhs to the rhs complex type.
1087       if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1088       return rhs;
1089     }
1090   }
1091   // Finally, we have two differing integer types.
1092   if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
1093     if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1094     return lhs;
1095   }
1096   if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
1097   return rhs;
1098 }
1099
1100 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
1101 // being closely modeled after the C99 spec:-). The odd characteristic of this 
1102 // routine is it effectively iqnores the qualifiers on the top level pointee.
1103 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1104 // FIXME: add a couple examples in this comment.
1105 Sema::AssignConvertType 
1106 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1107   QualType lhptee, rhptee;
1108   
1109   // get the "pointed to" type (ignoring qualifiers at the top level)
1110   lhptee = lhsType->getAsPointerType()->getPointeeType();
1111   rhptee = rhsType->getAsPointerType()->getPointeeType();
1112   
1113   // make sure we operate on the canonical type
1114   lhptee = lhptee.getCanonicalType();
1115   rhptee = rhptee.getCanonicalType();
1116
1117   AssignConvertType ConvTy = Compatible;
1118   
1119   // C99 6.5.16.1p1: This following citation is common to constraints 
1120   // 3 & 4 (below). ...and the type *pointed to* by the left has all the 
1121   // qualifiers of the type *pointed to* by the right; 
1122   // FIXME: Handle ASQualType
1123   if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) != 
1124        rhptee.getCVRQualifiers())
1125     ConvTy = CompatiblePointerDiscardsQualifiers;
1126
1127   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 
1128   // incomplete type and the other is a pointer to a qualified or unqualified 
1129   // version of void...
1130   if (lhptee->isVoidType()) {
1131     if (rhptee->isObjectType() || rhptee->isIncompleteType())
1132       return ConvTy;
1133     
1134     // As an extension, we allow cast to/from void* to function pointer.
1135     if (rhptee->isFunctionType())
1136       return FunctionVoidPointer;
1137   }
1138   
1139   if (rhptee->isVoidType()) {
1140     if (lhptee->isObjectType() || lhptee->isIncompleteType())
1141       return ConvTy;
1142
1143     // As an extension, we allow cast to/from void* to function pointer.
1144     if (lhptee->isFunctionType())
1145       return FunctionVoidPointer;
1146   }
1147   
1148   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 
1149   // unqualified versions of compatible types, ...
1150   if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 
1151                                   rhptee.getUnqualifiedType()))
1152     return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1153   return ConvTy;
1154 }
1155
1156 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 
1157 /// has code to accommodate several GCC extensions when type checking 
1158 /// pointers. Here are some objectionable examples that GCC considers warnings:
1159 ///
1160 ///  int a, *pint;
1161 ///  short *pshort;
1162 ///  struct foo *pfoo;
1163 ///
1164 ///  pint = pshort; // warning: assignment from incompatible pointer type
1165 ///  a = pint; // warning: assignment makes integer from pointer without a cast
1166 ///  pint = a; // warning: assignment makes pointer from integer without a cast
1167 ///  pint = pfoo; // warning: assignment from incompatible pointer type
1168 ///
1169 /// As a result, the code for dealing with pointers is more complex than the
1170 /// C99 spec dictates. 
1171 /// Note: the warning above turn into errors when -pedantic-errors is enabled. 
1172 ///
1173 Sema::AssignConvertType
1174 Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
1175   // Get canonical types.  We're not formatting these types, just comparing
1176   // them.
1177   lhsType = lhsType.getCanonicalType();
1178   rhsType = rhsType.getCanonicalType();
1179   
1180   if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
1181     return Compatible; // Common case: fast path an exact match.
1182
1183   if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1184     if (Context.referenceTypesAreCompatible(lhsType, rhsType))
1185       return Compatible;
1186     return Incompatible;
1187   }
1188   
1189   if (lhsType->isObjCQualifiedIdType() 
1190            || rhsType->isObjCQualifiedIdType()) {
1191     if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
1192       return Compatible;
1193     return Incompatible;
1194   }
1195
1196   if (lhsType->isVectorType() || rhsType->isVectorType()) {
1197     // For OCUVector, allow vector splats; float -> <n x float>
1198     if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1199       if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1200         return Compatible;
1201     }
1202     
1203     // If LHS and RHS are both vectors of integer or both vectors of floating
1204     // point types, and the total vector length is the same, allow the
1205     // conversion.  This is a bitcast; no bits are changed but the result type
1206     // is different.
1207     if (getLangOptions().LaxVectorConversions &&
1208         lhsType->isVectorType() && rhsType->isVectorType()) {
1209       if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1210           (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1211         if (Context.getTypeSize(lhsType, SourceLocation()) == 
1212             Context.getTypeSize(rhsType, SourceLocation()))
1213           return Compatible;
1214       }
1215     }
1216     return Incompatible;
1217   }      
1218   
1219   if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
1220     return Compatible;
1221   
1222   if (lhsType->isPointerType()) {
1223     if (rhsType->isIntegerType())
1224       return IntToPointer;
1225       
1226     if (rhsType->isPointerType())
1227       return CheckPointerTypesForAssignment(lhsType, rhsType);
1228     return Incompatible;
1229   }
1230
1231   if (rhsType->isPointerType()) {
1232     // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1233     if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1234       return PointerToInt;
1235
1236     if (lhsType->isPointerType()) 
1237       return CheckPointerTypesForAssignment(lhsType, rhsType);
1238     return Incompatible;
1239   }
1240   
1241   if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1242     if (Context.tagTypesAreCompatible(lhsType, rhsType))
1243       return Compatible;
1244   }
1245   return Incompatible;
1246 }
1247
1248 Sema::AssignConvertType
1249 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1250   // C99 6.5.16.1p1: the left operand is a pointer and the right is
1251   // a null pointer constant.
1252   if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType()) 
1253       && rExpr->isNullPointerConstant(Context)) {
1254     ImpCastExprToType(rExpr, lhsType);
1255     return Compatible;
1256   }
1257   // This check seems unnatural, however it is necessary to ensure the proper
1258   // conversion of functions/arrays. If the conversion were done for all
1259   // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
1260   // expressions that surpress this implicit conversion (&, sizeof).
1261   //
1262   // Suppress this for references: C99 8.5.3p5.  FIXME: revisit when references
1263   // are better understood.
1264   if (!lhsType->isReferenceType())
1265     DefaultFunctionArrayConversion(rExpr);
1266
1267   Sema::AssignConvertType result =
1268     CheckAssignmentConstraints(lhsType, rExpr->getType());
1269   
1270   // C99 6.5.16.1p2: The value of the right operand is converted to the
1271   // type of the assignment expression.
1272   if (rExpr->getType() != lhsType)
1273     ImpCastExprToType(rExpr, lhsType);
1274   return result;
1275 }
1276
1277 Sema::AssignConvertType
1278 Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1279   return CheckAssignmentConstraints(lhsType, rhsType);
1280 }
1281
1282 QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1283   Diag(loc, diag::err_typecheck_invalid_operands, 
1284        lex->getType().getAsString(), rex->getType().getAsString(),
1285        lex->getSourceRange(), rex->getSourceRange());
1286   return QualType();
1287 }
1288
1289 inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex, 
1290                                                               Expr *&rex) {
1291   QualType lhsType = lex->getType(), rhsType = rex->getType();
1292   
1293   // make sure the vector types are identical. 
1294   if (lhsType == rhsType)
1295     return lhsType;
1296
1297   // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1298   // promote the rhs to the vector type.
1299   if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1300     if (V->getElementType().getCanonicalType().getTypePtr()
1301         == rhsType.getCanonicalType().getTypePtr()) {
1302       ImpCastExprToType(rex, lhsType);
1303       return lhsType;
1304     }
1305   }
1306
1307   // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1308   // promote the lhs to the vector type.
1309   if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1310     if (V->getElementType().getCanonicalType().getTypePtr()
1311         == lhsType.getCanonicalType().getTypePtr()) {
1312       ImpCastExprToType(lex, rhsType);
1313       return rhsType;
1314     }
1315   }
1316
1317   // You cannot convert between vector values of different size.
1318   Diag(loc, diag::err_typecheck_vector_not_convertable, 
1319        lex->getType().getAsString(), rex->getType().getAsString(),
1320        lex->getSourceRange(), rex->getSourceRange());
1321   return QualType();
1322 }    
1323
1324 inline QualType Sema::CheckMultiplyDivideOperands(
1325   Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 
1326 {
1327   QualType lhsType = lex->getType(), rhsType = rex->getType();
1328
1329   if (lhsType->isVectorType() || rhsType->isVectorType())
1330     return CheckVectorOperands(loc, lex, rex);
1331     
1332   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1333   
1334   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1335     return compType;
1336   return InvalidOperands(loc, lex, rex);
1337 }
1338
1339 inline QualType Sema::CheckRemainderOperands(
1340   Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 
1341 {
1342   QualType lhsType = lex->getType(), rhsType = rex->getType();
1343
1344   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1345   
1346   if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1347     return compType;
1348   return InvalidOperands(loc, lex, rex);
1349 }
1350
1351 inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
1352   Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 
1353 {
1354   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1355     return CheckVectorOperands(loc, lex, rex);
1356
1357   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1358   
1359   // handle the common case first (both operands are arithmetic).
1360   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1361     return compType;
1362
1363   if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1364     return lex->getType();
1365   if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1366     return rex->getType();
1367   return InvalidOperands(loc, lex, rex);
1368 }
1369
1370 inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
1371   Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 
1372 {
1373   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1374     return CheckVectorOperands(loc, lex, rex);
1375     
1376   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1377   
1378   // Enforce type constraints: C99 6.5.6p3.
1379   
1380   // Handle the common case first (both operands are arithmetic).
1381   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1382     return compType;
1383   
1384   // Either ptr - int   or   ptr - ptr.
1385   if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1386     QualType lpointee = LHSPTy->getPointeeType();
1387     
1388     // The LHS must be an object type, not incomplete, function, etc.
1389     if (!lpointee->isObjectType()) {
1390       // Handle the GNU void* extension.
1391       if (lpointee->isVoidType()) {
1392         Diag(loc, diag::ext_gnu_void_ptr, 
1393              lex->getSourceRange(), rex->getSourceRange());
1394       } else {
1395         Diag(loc, diag::err_typecheck_sub_ptr_object,
1396              lex->getType().getAsString(), lex->getSourceRange());
1397         return QualType();
1398       }
1399     }
1400
1401     // The result type of a pointer-int computation is the pointer type.
1402     if (rex->getType()->isIntegerType())
1403       return lex->getType();
1404     
1405     // Handle pointer-pointer subtractions.
1406     if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1407       QualType rpointee = RHSPTy->getPointeeType();
1408       
1409       // RHS must be an object type, unless void (GNU).
1410       if (!rpointee->isObjectType()) {
1411         // Handle the GNU void* extension.
1412         if (rpointee->isVoidType()) {
1413           if (!lpointee->isVoidType())
1414             Diag(loc, diag::ext_gnu_void_ptr, 
1415                  lex->getSourceRange(), rex->getSourceRange());
1416         } else {
1417           Diag(loc, diag::err_typecheck_sub_ptr_object,
1418                rex->getType().getAsString(), rex->getSourceRange());
1419           return QualType();
1420         }
1421       }
1422       
1423       // Pointee types must be compatible.
1424       if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(), 
1425                                       rpointee.getUnqualifiedType())) {
1426         Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1427              lex->getType().getAsString(), rex->getType().getAsString(),
1428              lex->getSourceRange(), rex->getSourceRange());
1429         return QualType();
1430       }
1431       
1432       return Context.getPointerDiffType();
1433     }
1434   }
1435   
1436   return InvalidOperands(loc, lex, rex);
1437 }
1438
1439 inline QualType Sema::CheckShiftOperands( // C99 6.5.7
1440   Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1441   // C99 6.5.7p2: Each of the operands shall have integer type.
1442   if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1443     return InvalidOperands(loc, lex, rex);
1444   
1445   // Shifts don't perform usual arithmetic conversions, they just do integer
1446   // promotions on each operand. C99 6.5.7p3
1447   if (!isCompAssign)
1448     UsualUnaryConversions(lex);
1449   UsualUnaryConversions(rex);
1450   
1451   // "The type of the result is that of the promoted left operand."
1452   return lex->getType();
1453 }
1454
1455 inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1456   Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
1457 {
1458   // C99 6.5.8p3 / C99 6.5.9p4
1459   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1460     UsualArithmeticConversions(lex, rex);
1461   else {
1462     UsualUnaryConversions(lex);
1463     UsualUnaryConversions(rex);
1464   }
1465   QualType lType = lex->getType();
1466   QualType rType = rex->getType();
1467   
1468   // For non-floating point types, check for self-comparisons of the form
1469   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
1470   // often indicate logic errors in the program.
1471   if (!lType->isFloatingType()) {
1472     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1473       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1474         if (DRL->getDecl() == DRR->getDecl())
1475           Diag(loc, diag::warn_selfcomparison);      
1476   }
1477   
1478   if (isRelational) {
1479     if (lType->isRealType() && rType->isRealType())
1480       return Context.IntTy;
1481   } else {
1482     // Check for comparisons of floating point operands using != and ==.
1483     if (lType->isFloatingType()) {
1484       assert (rType->isFloatingType());
1485       CheckFloatComparison(loc,lex,rex);
1486     }
1487     
1488     if (lType->isArithmeticType() && rType->isArithmeticType())
1489       return Context.IntTy;
1490   }
1491   
1492   bool LHSIsNull = lex->isNullPointerConstant(Context);
1493   bool RHSIsNull = rex->isNullPointerConstant(Context);
1494   
1495   // All of the following pointer related warnings are GCC extensions, except
1496   // when handling null pointer constants. One day, we can consider making them
1497   // errors (when -pedantic-errors is enabled).
1498   if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
1499     QualType lpointee = lType->getAsPointerType()->getPointeeType();
1500     QualType rpointee = rType->getAsPointerType()->getPointeeType();
1501     
1502     if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
1503         !lpointee->isVoidType() && !lpointee->isVoidType() &&
1504         !Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1505                                     rpointee.getUnqualifiedType())) {
1506       Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1507            lType.getAsString(), rType.getAsString(),
1508            lex->getSourceRange(), rex->getSourceRange());
1509     }
1510     ImpCastExprToType(rex, lType); // promote the pointer to pointer
1511     return Context.IntTy;
1512   }
1513   if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1514       && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1515     ImpCastExprToType(rex, lType); 
1516     return Context.IntTy;
1517   }
1518   if (lType->isPointerType() && rType->isIntegerType()) {
1519     if (!RHSIsNull)
1520       Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1521            lType.getAsString(), rType.getAsString(),
1522            lex->getSourceRange(), rex->getSourceRange());
1523     ImpCastExprToType(rex, lType); // promote the integer to pointer
1524     return Context.IntTy;
1525   }
1526   if (lType->isIntegerType() && rType->isPointerType()) {
1527     if (!LHSIsNull)
1528       Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1529            lType.getAsString(), rType.getAsString(),
1530            lex->getSourceRange(), rex->getSourceRange());
1531     ImpCastExprToType(lex, rType); // promote the integer to pointer
1532     return Context.IntTy;
1533   }
1534   return InvalidOperands(loc, lex, rex);
1535 }
1536
1537 inline QualType Sema::CheckBitwiseOperands(
1538   Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 
1539 {
1540   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1541     return CheckVectorOperands(loc, lex, rex);
1542
1543   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1544   
1545   if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1546     return compType;
1547   return InvalidOperands(loc, lex, rex);
1548 }
1549
1550 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1551   Expr *&lex, Expr *&rex, SourceLocation loc) 
1552 {
1553   UsualUnaryConversions(lex);
1554   UsualUnaryConversions(rex);
1555   
1556   if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1557     return Context.IntTy;
1558   return InvalidOperands(loc, lex, rex);
1559 }
1560
1561 inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1562   Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType) 
1563 {
1564   QualType lhsType = lex->getType();
1565   QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1566   Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(); 
1567
1568   switch (mlval) { // C99 6.5.16p2
1569   case Expr::MLV_Valid: 
1570     break;
1571   case Expr::MLV_ConstQualified:
1572     Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1573     return QualType();
1574   case Expr::MLV_ArrayType: 
1575     Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1576          lhsType.getAsString(), lex->getSourceRange());
1577     return QualType(); 
1578   case Expr::MLV_NotObjectType: 
1579     Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1580          lhsType.getAsString(), lex->getSourceRange());
1581     return QualType();
1582   case Expr::MLV_InvalidExpression:
1583     Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1584          lex->getSourceRange());
1585     return QualType();
1586   case Expr::MLV_IncompleteType:
1587   case Expr::MLV_IncompleteVoidType:
1588     Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1589          lhsType.getAsString(), lex->getSourceRange());
1590     return QualType();
1591   case Expr::MLV_DuplicateVectorComponents:
1592     Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1593          lex->getSourceRange());
1594     return QualType();
1595   }
1596
1597   AssignConvertType ConvTy;
1598   if (compoundType.isNull())
1599     ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1600   else
1601     ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1602
1603   if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1604                                rex, "assigning"))
1605     return QualType();
1606   
1607   // C99 6.5.16p3: The type of an assignment expression is the type of the
1608   // left operand unless the left operand has qualified type, in which case
1609   // it is the unqualified version of the type of the left operand. 
1610   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1611   // is converted to the type of the assignment expression (above).
1612   // C++ 5.17p1: the type of the assignment expression is that of its left
1613   // oprdu.
1614   return lhsType.getUnqualifiedType();
1615 }
1616
1617 inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1618   Expr *&lex, Expr *&rex, SourceLocation loc) {
1619   UsualUnaryConversions(rex);
1620   return rex->getType();
1621 }
1622
1623 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1624 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1625 QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1626   QualType resType = op->getType();
1627   assert(!resType.isNull() && "no type for increment/decrement expression");
1628
1629   // C99 6.5.2.4p1: We allow complex as a GCC extension.
1630   if (const PointerType *pt = resType->getAsPointerType()) {
1631     if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1632       Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1633            resType.getAsString(), op->getSourceRange());
1634       return QualType();
1635     }
1636   } else if (!resType->isRealType()) {
1637     if (resType->isComplexType()) 
1638       // C99 does not support ++/-- on complex types.
1639       Diag(OpLoc, diag::ext_integer_increment_complex,
1640            resType.getAsString(), op->getSourceRange());
1641     else {
1642       Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1643            resType.getAsString(), op->getSourceRange());
1644       return QualType();
1645     }
1646   }
1647   // At this point, we know we have a real, complex or pointer type. 
1648   // Now make sure the operand is a modifiable lvalue.
1649   Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1650   if (mlval != Expr::MLV_Valid) {
1651     // FIXME: emit a more precise diagnostic...
1652     Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1653          op->getSourceRange());
1654     return QualType();
1655   }
1656   return resType;
1657 }
1658
1659 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
1660 /// This routine allows us to typecheck complex/recursive expressions
1661 /// where the declaration is needed for type checking. Here are some
1662 /// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1663 static ValueDecl *getPrimaryDecl(Expr *e) {
1664   switch (e->getStmtClass()) {
1665   case Stmt::DeclRefExprClass:
1666     return cast<DeclRefExpr>(e)->getDecl();
1667   case Stmt::MemberExprClass:
1668     // Fields cannot be declared with a 'register' storage class.
1669     // &X->f is always ok, even if X is declared register.
1670     if (cast<MemberExpr>(e)->isArrow())
1671       return 0;
1672     return getPrimaryDecl(cast<MemberExpr>(e)->getBase());
1673   case Stmt::ArraySubscriptExprClass: {
1674     // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1675   
1676     ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(e)->getBase());
1677     if (!VD || VD->getType()->isPointerType())
1678       return 0;
1679     else
1680       return VD;
1681   }
1682   case Stmt::UnaryOperatorClass:
1683     return getPrimaryDecl(cast<UnaryOperator>(e)->getSubExpr());
1684   case Stmt::ParenExprClass:
1685     return getPrimaryDecl(cast<ParenExpr>(e)->getSubExpr());
1686   case Stmt::ImplicitCastExprClass:
1687     // &X[4] when X is an array, has an implicit cast from array to pointer.
1688     return getPrimaryDecl(cast<ImplicitCastExpr>(e)->getSubExpr());
1689   default:
1690     return 0;
1691   }
1692 }
1693
1694 /// CheckAddressOfOperand - The operand of & must be either a function
1695 /// designator or an lvalue designating an object. If it is an lvalue, the 
1696 /// object cannot be declared with storage class register or be a bit field.
1697 /// Note: The usual conversions are *not* applied to the operand of the & 
1698 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1699 QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1700   if (getLangOptions().C99) {
1701     // Implement C99-only parts of addressof rules.
1702     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1703       if (uOp->getOpcode() == UnaryOperator::Deref)
1704         // Per C99 6.5.3.2, the address of a deref always returns a valid result
1705         // (assuming the deref expression is valid).
1706         return uOp->getSubExpr()->getType();
1707     }
1708     // Technically, there should be a check for array subscript
1709     // expressions here, but the result of one is always an lvalue anyway.
1710   }
1711   ValueDecl *dcl = getPrimaryDecl(op);
1712   Expr::isLvalueResult lval = op->isLvalue();
1713   
1714   if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1715     if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1716       // FIXME: emit more specific diag...
1717       Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof, 
1718            op->getSourceRange());
1719       return QualType();
1720     }
1721   } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1722     if (MemExpr->getMemberDecl()->isBitField()) {
1723       Diag(OpLoc, diag::err_typecheck_address_of, 
1724            std::string("bit-field"), op->getSourceRange());
1725       return QualType();
1726     }
1727   // Check for Apple extension for accessing vector components.
1728   } else if (isa<ArraySubscriptExpr>(op) &&
1729            cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1730     Diag(OpLoc, diag::err_typecheck_address_of, 
1731          std::string("vector"), op->getSourceRange());
1732     return QualType();
1733   } else if (dcl) { // C99 6.5.3.2p1
1734     // We have an lvalue with a decl. Make sure the decl is not declared 
1735     // with the register storage-class specifier.
1736     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1737       if (vd->getStorageClass() == VarDecl::Register) {
1738         Diag(OpLoc, diag::err_typecheck_address_of, 
1739              std::string("register variable"), op->getSourceRange());
1740         return QualType();
1741       }
1742     } else 
1743       assert(0 && "Unknown/unexpected decl type");
1744   }
1745   // If the operand has type "type", the result has type "pointer to type".
1746   return Context.getPointerType(op->getType());
1747 }
1748
1749 QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1750   UsualUnaryConversions(op);
1751   QualType qType = op->getType();
1752   
1753   if (const PointerType *PT = qType->getAsPointerType()) {
1754     // Note that per both C89 and C99, this is always legal, even
1755     // if ptype is an incomplete type or void.
1756     // It would be possible to warn about dereferencing a
1757     // void pointer, but it's completely well-defined,
1758     // and such a warning is unlikely to catch any mistakes.
1759     return PT->getPointeeType();
1760   }
1761   Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer, 
1762        qType.getAsString(), op->getSourceRange());
1763   return QualType();
1764 }
1765
1766 static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1767   tok::TokenKind Kind) {
1768   BinaryOperator::Opcode Opc;
1769   switch (Kind) {
1770   default: assert(0 && "Unknown binop!");
1771   case tok::star:                 Opc = BinaryOperator::Mul; break;
1772   case tok::slash:                Opc = BinaryOperator::Div; break;
1773   case tok::percent:              Opc = BinaryOperator::Rem; break;
1774   case tok::plus:                 Opc = BinaryOperator::Add; break;
1775   case tok::minus:                Opc = BinaryOperator::Sub; break;
1776   case tok::lessless:             Opc = BinaryOperator::Shl; break;
1777   case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
1778   case tok::lessequal:            Opc = BinaryOperator::LE; break;
1779   case tok::less:                 Opc = BinaryOperator::LT; break;
1780   case tok::greaterequal:         Opc = BinaryOperator::GE; break;
1781   case tok::greater:              Opc = BinaryOperator::GT; break;
1782   case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
1783   case tok::equalequal:           Opc = BinaryOperator::EQ; break;
1784   case tok::amp:                  Opc = BinaryOperator::And; break;
1785   case tok::caret:                Opc = BinaryOperator::Xor; break;
1786   case tok::pipe:                 Opc = BinaryOperator::Or; break;
1787   case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
1788   case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
1789   case tok::equal:                Opc = BinaryOperator::Assign; break;
1790   case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
1791   case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
1792   case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
1793   case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
1794   case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
1795   case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
1796   case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
1797   case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
1798   case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
1799   case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
1800   case tok::comma:                Opc = BinaryOperator::Comma; break;
1801   }
1802   return Opc;
1803 }
1804
1805 static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1806   tok::TokenKind Kind) {
1807   UnaryOperator::Opcode Opc;
1808   switch (Kind) {
1809   default: assert(0 && "Unknown unary op!");
1810   case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
1811   case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
1812   case tok::amp:          Opc = UnaryOperator::AddrOf; break;
1813   case tok::star:         Opc = UnaryOperator::Deref; break;
1814   case tok::plus:         Opc = UnaryOperator::Plus; break;
1815   case tok::minus:        Opc = UnaryOperator::Minus; break;
1816   case tok::tilde:        Opc = UnaryOperator::Not; break;
1817   case tok::exclaim:      Opc = UnaryOperator::LNot; break;
1818   case tok::kw_sizeof:    Opc = UnaryOperator::SizeOf; break;
1819   case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1820   case tok::kw___real:    Opc = UnaryOperator::Real; break;
1821   case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
1822   case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1823   }
1824   return Opc;
1825 }
1826
1827 // Binary Operators.  'Tok' is the token for the operator.
1828 Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1829                                     ExprTy *LHS, ExprTy *RHS) {
1830   BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1831   Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1832
1833   assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1834   assert((rhs != 0) && "ActOnBinOp(): missing right expression");
1835
1836   QualType ResultTy;  // Result type of the binary operator.
1837   QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
1838   
1839   switch (Opc) {
1840   default:
1841     assert(0 && "Unknown binary expr!");
1842   case BinaryOperator::Assign:
1843     ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1844     break;
1845   case BinaryOperator::Mul: 
1846   case BinaryOperator::Div:
1847     ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1848     break;
1849   case BinaryOperator::Rem:
1850     ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1851     break;
1852   case BinaryOperator::Add:
1853     ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1854     break;
1855   case BinaryOperator::Sub:
1856     ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1857     break;
1858   case BinaryOperator::Shl: 
1859   case BinaryOperator::Shr:
1860     ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1861     break;
1862   case BinaryOperator::LE:
1863   case BinaryOperator::LT:
1864   case BinaryOperator::GE:
1865   case BinaryOperator::GT:
1866     ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
1867     break;
1868   case BinaryOperator::EQ:
1869   case BinaryOperator::NE:
1870     ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
1871     break;
1872   case BinaryOperator::And:
1873   case BinaryOperator::Xor:
1874   case BinaryOperator::Or:
1875     ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1876     break;
1877   case BinaryOperator::LAnd:
1878   case BinaryOperator::LOr:
1879     ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1880     break;
1881   case BinaryOperator::MulAssign:
1882   case BinaryOperator::DivAssign:
1883     CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
1884     if (!CompTy.isNull())
1885       ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1886     break;
1887   case BinaryOperator::RemAssign:
1888     CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
1889     if (!CompTy.isNull())
1890       ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1891     break;
1892   case BinaryOperator::AddAssign:
1893     CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
1894     if (!CompTy.isNull())
1895       ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1896     break;
1897   case BinaryOperator::SubAssign:
1898     CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
1899     if (!CompTy.isNull())
1900       ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1901     break;
1902   case BinaryOperator::ShlAssign:
1903   case BinaryOperator::ShrAssign:
1904     CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
1905     if (!CompTy.isNull())
1906       ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1907     break;
1908   case BinaryOperator::AndAssign:
1909   case BinaryOperator::XorAssign:
1910   case BinaryOperator::OrAssign:
1911     CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
1912     if (!CompTy.isNull())
1913       ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1914     break;
1915   case BinaryOperator::Comma:
1916     ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1917     break;
1918   }
1919   if (ResultTy.isNull())
1920     return true;
1921   if (CompTy.isNull())
1922     return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
1923   else
1924     return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
1925 }
1926
1927 // Unary Operators.  'Tok' is the token for the operator.
1928 Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1929                                       ExprTy *input) {
1930   Expr *Input = (Expr*)input;
1931   UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1932   QualType resultType;
1933   switch (Opc) {
1934   default:
1935     assert(0 && "Unimplemented unary expr!");
1936   case UnaryOperator::PreInc:
1937   case UnaryOperator::PreDec:
1938     resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1939     break;
1940   case UnaryOperator::AddrOf: 
1941     resultType = CheckAddressOfOperand(Input, OpLoc);
1942     break;
1943   case UnaryOperator::Deref: 
1944     DefaultFunctionArrayConversion(Input);
1945     resultType = CheckIndirectionOperand(Input, OpLoc);
1946     break;
1947   case UnaryOperator::Plus:
1948   case UnaryOperator::Minus:
1949     UsualUnaryConversions(Input);
1950     resultType = Input->getType();
1951     if (!resultType->isArithmeticType())  // C99 6.5.3.3p1
1952       return Diag(OpLoc, diag::err_typecheck_unary_expr, 
1953                   resultType.getAsString());
1954     break;
1955   case UnaryOperator::Not: // bitwise complement
1956     UsualUnaryConversions(Input);
1957     resultType = Input->getType();
1958     // C99 6.5.3.3p1. We allow complex as a GCC extension.
1959     if (!resultType->isIntegerType()) {
1960       if (resultType->isComplexType())
1961         // C99 does not support '~' for complex conjugation.
1962         Diag(OpLoc, diag::ext_integer_complement_complex,
1963                     resultType.getAsString());
1964       else
1965         return Diag(OpLoc, diag::err_typecheck_unary_expr,
1966                     resultType.getAsString());
1967     }
1968     break;
1969   case UnaryOperator::LNot: // logical negation
1970     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1971     DefaultFunctionArrayConversion(Input);
1972     resultType = Input->getType();
1973     if (!resultType->isScalarType()) // C99 6.5.3.3p1
1974       return Diag(OpLoc, diag::err_typecheck_unary_expr,
1975                   resultType.getAsString());
1976     // LNot always has type int. C99 6.5.3.3p5.
1977     resultType = Context.IntTy;
1978     break;
1979   case UnaryOperator::SizeOf:
1980     resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1981     break;
1982   case UnaryOperator::AlignOf:
1983     resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1984     break;
1985   case UnaryOperator::Real:
1986   case UnaryOperator::Imag:
1987     resultType = CheckRealImagOperand(Input, OpLoc);
1988     break;
1989   case UnaryOperator::Extension:
1990     resultType = Input->getType();
1991     break;
1992   }
1993   if (resultType.isNull())
1994     return true;
1995   return new UnaryOperator(Input, Opc, resultType, OpLoc);
1996 }
1997
1998 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1999 Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 
2000                                       SourceLocation LabLoc,
2001                                       IdentifierInfo *LabelII) {
2002   // Look up the record for this label identifier.
2003   LabelStmt *&LabelDecl = LabelMap[LabelII];
2004   
2005   // If we haven't seen this label yet, create a forward reference.
2006   if (LabelDecl == 0)
2007     LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2008   
2009   // Create the AST node.  The address of a label always has type 'void*'.
2010   return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2011                            Context.getPointerType(Context.VoidTy));
2012 }
2013
2014 Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
2015                                      SourceLocation RPLoc) { // "({..})"
2016   Stmt *SubStmt = static_cast<Stmt*>(substmt);
2017   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2018   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2019
2020   // FIXME: there are a variety of strange constraints to enforce here, for
2021   // example, it is not possible to goto into a stmt expression apparently.
2022   // More semantic analysis is needed.
2023   
2024   // FIXME: the last statement in the compount stmt has its value used.  We
2025   // should not warn about it being unused.
2026
2027   // If there are sub stmts in the compound stmt, take the type of the last one
2028   // as the type of the stmtexpr.
2029   QualType Ty = Context.VoidTy;
2030   
2031   if (!Compound->body_empty())
2032     if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2033       Ty = LastExpr->getType();
2034   
2035   return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2036 }
2037
2038 Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
2039                                             SourceLocation TypeLoc,
2040                                             TypeTy *argty,
2041                                             OffsetOfComponent *CompPtr,
2042                                             unsigned NumComponents,
2043                                             SourceLocation RPLoc) {
2044   QualType ArgTy = QualType::getFromOpaquePtr(argty);
2045   assert(!ArgTy.isNull() && "Missing type argument!");
2046   
2047   // We must have at least one component that refers to the type, and the first
2048   // one is known to be a field designator.  Verify that the ArgTy represents
2049   // a struct/union/class.
2050   if (!ArgTy->isRecordType())
2051     return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2052   
2053   // Otherwise, create a compound literal expression as the base, and
2054   // iteratively process the offsetof designators.
2055   Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
2056   
2057   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2058   // GCC extension, diagnose them.
2059   if (NumComponents != 1)
2060     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2061          SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2062   
2063   for (unsigned i = 0; i != NumComponents; ++i) {
2064     const OffsetOfComponent &OC = CompPtr[i];
2065     if (OC.isBrackets) {
2066       // Offset of an array sub-field.  TODO: Should we allow vector elements?
2067       const ArrayType *AT = Res->getType()->getAsArrayType();
2068       if (!AT) {
2069         delete Res;
2070         return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2071                     Res->getType().getAsString());
2072       }
2073       
2074       // FIXME: C++: Verify that operator[] isn't overloaded.
2075
2076       // C99 6.5.2.1p1
2077       Expr *Idx = static_cast<Expr*>(OC.U.E);
2078       if (!Idx->getType()->isIntegerType())
2079         return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2080                     Idx->getSourceRange());
2081       
2082       Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2083       continue;
2084     }
2085     
2086     const RecordType *RC = Res->getType()->getAsRecordType();
2087     if (!RC) {
2088       delete Res;
2089       return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2090                   Res->getType().getAsString());
2091     }
2092       
2093     // Get the decl corresponding to this.
2094     RecordDecl *RD = RC->getDecl();
2095     FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2096     if (!MemberDecl)
2097       return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2098                   OC.U.IdentInfo->getName(),
2099                   SourceRange(OC.LocStart, OC.LocEnd));
2100     
2101     // FIXME: C++: Verify that MemberDecl isn't a static field.
2102     // FIXME: Verify that MemberDecl isn't a bitfield.
2103     // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2104     // matter here.
2105     Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
2106   }
2107   
2108   return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2109                            BuiltinLoc);
2110 }
2111
2112
2113 Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 
2114                                                 TypeTy *arg1, TypeTy *arg2,
2115                                                 SourceLocation RPLoc) {
2116   QualType argT1 = QualType::getFromOpaquePtr(arg1);
2117   QualType argT2 = QualType::getFromOpaquePtr(arg2);
2118   
2119   assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2120   
2121   return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
2122 }
2123
2124 Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 
2125                                        ExprTy *expr1, ExprTy *expr2,
2126                                        SourceLocation RPLoc) {
2127   Expr *CondExpr = static_cast<Expr*>(cond);
2128   Expr *LHSExpr = static_cast<Expr*>(expr1);
2129   Expr *RHSExpr = static_cast<Expr*>(expr2);
2130   
2131   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2132
2133   // The conditional expression is required to be a constant expression.
2134   llvm::APSInt condEval(32);
2135   SourceLocation ExpLoc;
2136   if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2137     return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2138                  CondExpr->getSourceRange());
2139
2140   // If the condition is > zero, then the AST type is the same as the LSHExpr.
2141   QualType resType = condEval.getZExtValue() ? LHSExpr->getType() : 
2142                                                RHSExpr->getType();
2143   return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2144 }
2145
2146 /// ExprsMatchFnType - return true if the Exprs in array Args have
2147 /// QualTypes that match the QualTypes of the arguments of the FnType.
2148 /// The number of arguments has already been validated to match the number of
2149 /// arguments in FnType.
2150 static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
2151   unsigned NumParams = FnType->getNumArgs();
2152   for (unsigned i = 0; i != NumParams; ++i)
2153     if (Args[i]->getType().getCanonicalType() != 
2154         FnType->getArgType(i).getCanonicalType())
2155       return false;
2156   return true;
2157 }
2158
2159 Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2160                                          SourceLocation *CommaLocs,
2161                                          SourceLocation BuiltinLoc,
2162                                          SourceLocation RParenLoc) {
2163   // __builtin_overload requires at least 2 arguments
2164   if (NumArgs < 2)
2165     return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2166                 SourceRange(BuiltinLoc, RParenLoc));
2167
2168   // The first argument is required to be a constant expression.  It tells us
2169   // the number of arguments to pass to each of the functions to be overloaded.
2170   Expr **Args = reinterpret_cast<Expr**>(args);
2171   Expr *NParamsExpr = Args[0];
2172   llvm::APSInt constEval(32);
2173   SourceLocation ExpLoc;
2174   if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2175     return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2176                 NParamsExpr->getSourceRange());
2177   
2178   // Verify that the number of parameters is > 0
2179   unsigned NumParams = constEval.getZExtValue();
2180   if (NumParams == 0)
2181     return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2182                 NParamsExpr->getSourceRange());
2183   // Verify that we have at least 1 + NumParams arguments to the builtin.
2184   if ((NumParams + 1) > NumArgs)
2185     return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2186                 SourceRange(BuiltinLoc, RParenLoc));
2187
2188   // Figure out the return type, by matching the args to one of the functions
2189   // listed after the parameters.
2190   OverloadExpr *OE = 0;
2191   for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2192     // UsualUnaryConversions will convert the function DeclRefExpr into a 
2193     // pointer to function.
2194     Expr *Fn = UsualUnaryConversions(Args[i]);
2195     FunctionTypeProto *FnType = 0;
2196     if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2197       QualType PointeeType = PT->getPointeeType().getCanonicalType();
2198       FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2199     }
2200  
2201     // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2202     // parameters, and the number of parameters must match the value passed to
2203     // the builtin.
2204     if (!FnType || (FnType->getNumArgs() != NumParams))
2205       return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype, 
2206                   Fn->getSourceRange());
2207
2208     // Scan the parameter list for the FunctionType, checking the QualType of
2209     // each parameter against the QualTypes of the arguments to the builtin.
2210     // If they match, return a new OverloadExpr.
2211     if (ExprsMatchFnType(Args+1, FnType)) {
2212       if (OE)
2213         return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2214                     OE->getFn()->getSourceRange());
2215       // Remember our match, and continue processing the remaining arguments
2216       // to catch any errors.
2217       OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2218                             BuiltinLoc, RParenLoc);
2219     }
2220   }
2221   // Return the newly created OverloadExpr node, if we succeded in matching
2222   // exactly one of the candidate functions.
2223   if (OE)
2224     return OE;
2225
2226   // If we didn't find a matching function Expr in the __builtin_overload list
2227   // the return an error.
2228   std::string typeNames;
2229   for (unsigned i = 0; i != NumParams; ++i) {
2230     if (i != 0) typeNames += ", ";
2231     typeNames += Args[i+1]->getType().getAsString();
2232   }
2233
2234   return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2235               SourceRange(BuiltinLoc, RParenLoc));
2236 }
2237
2238 Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2239                                   ExprTy *expr, TypeTy *type,
2240                                   SourceLocation RPLoc) {
2241   Expr *E = static_cast<Expr*>(expr);
2242   QualType T = QualType::getFromOpaquePtr(type);
2243
2244   InitBuiltinVaListType();
2245   
2246   if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2247       != Compatible)
2248     return Diag(E->getLocStart(),
2249                 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2250                 E->getType().getAsString(),
2251                 E->getSourceRange());
2252   
2253   // FIXME: Warn if a non-POD type is passed in.
2254   
2255   return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2256 }
2257
2258 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2259                                     SourceLocation Loc,
2260                                     QualType DstType, QualType SrcType,
2261                                     Expr *SrcExpr, const char *Flavor) {
2262   // Decode the result (notice that AST's are still created for extensions).
2263   bool isInvalid = false;
2264   unsigned DiagKind;
2265   switch (ConvTy) {
2266   default: assert(0 && "Unknown conversion type");
2267   case Compatible: return false;
2268   case PointerToInt:
2269     DiagKind = diag::ext_typecheck_convert_pointer_int;
2270     break;
2271   case IntToPointer:
2272     DiagKind = diag::ext_typecheck_convert_int_pointer;
2273     break;
2274   case IncompatiblePointer:
2275     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2276     break;
2277   case FunctionVoidPointer:
2278     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2279     break;
2280   case CompatiblePointerDiscardsQualifiers:
2281     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2282     break;
2283   case Incompatible:
2284     DiagKind = diag::err_typecheck_convert_incompatible;
2285     isInvalid = true;
2286     break;
2287   }
2288   
2289   Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2290        SrcExpr->getSourceRange());
2291   return isInvalid;
2292 }
2293