SemaExpr.cpp revision 253fc4d146d4815c9a4ef15a7196edb2e7831865
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 "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Designator.h"
26#include "clang/Parse/Scope.h"
27using namespace clang;
28
29/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
41  // See if the decl is deprecated.
42  if (D->getAttr<DeprecatedAttr>()) {
43    // Implementing deprecated stuff requires referencing deprecated
44    // stuff. Don't warn if we are implementing a deprecated
45    // construct.
46    bool isSilenced = false;
47
48    if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49      // If this reference happens *in* a deprecated function or method, don't
50      // warn.
51      isSilenced = ND->getAttr<DeprecatedAttr>();
52
53      // If this is an Objective-C method implementation, check to see if the
54      // method was deprecated on the declaration, not the definition.
55      if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56        // The semantic decl context of a ObjCMethodDecl is the
57        // ObjCImplementationDecl.
58        if (ObjCImplementationDecl *Impl
59              = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
61          MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62                                                    MD->isInstanceMethod());
63          isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64        }
65      }
66    }
67
68    if (!isSilenced)
69      Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70  }
71
72  // See if this is a deleted function.
73  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74    if (FD->isDeleted()) {
75      Diag(Loc, diag::err_deleted_function_use);
76      Diag(D->getLocation(), diag::note_unavailable_here) << true;
77      return true;
78    }
79  }
80
81  // See if the decl is unavailable
82  if (D->getAttr<UnavailableAttr>()) {
83    Diag(Loc, diag::warn_unavailable) << D->getDeclName();
84    Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85  }
86
87  return false;
88}
89
90SourceRange Sema::getExprRange(ExprTy *E) const {
91  Expr *Ex = (Expr *)E;
92  return Ex? Ex->getSourceRange() : SourceRange();
93}
94
95//===----------------------------------------------------------------------===//
96//  Standard Promotions and Conversions
97//===----------------------------------------------------------------------===//
98
99/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
100void Sema::DefaultFunctionArrayConversion(Expr *&E) {
101  QualType Ty = E->getType();
102  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
103
104  if (Ty->isFunctionType())
105    ImpCastExprToType(E, Context.getPointerType(Ty));
106  else if (Ty->isArrayType()) {
107    // In C90 mode, arrays only promote to pointers if the array expression is
108    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
109    // type 'array of type' is converted to an expression that has type 'pointer
110    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
111    // that has type 'array of type' ...".  The relevant change is "an lvalue"
112    // (C90) to "an expression" (C99).
113    //
114    // C++ 4.2p1:
115    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
116    // T" can be converted to an rvalue of type "pointer to T".
117    //
118    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
119        E->isLvalue(Context) == Expr::LV_Valid)
120      ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
121  }
122}
123
124/// UsualUnaryConversions - Performs various conversions that are common to most
125/// operators (C99 6.3). The conversions of array and function types are
126/// sometimes surpressed. For example, the array->pointer conversion doesn't
127/// apply if the array is an argument to the sizeof or address (&) operators.
128/// In these instances, this routine should *not* be called.
129Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
130  QualType Ty = Expr->getType();
131  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
132
133  if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
134    ImpCastExprToType(Expr, Context.IntTy);
135  else
136    DefaultFunctionArrayConversion(Expr);
137
138  return Expr;
139}
140
141/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
142/// do not have a prototype. Arguments that have type float are promoted to
143/// double. All other argument types are converted by UsualUnaryConversions().
144void Sema::DefaultArgumentPromotion(Expr *&Expr) {
145  QualType Ty = Expr->getType();
146  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
147
148  // If this is a 'float' (CVR qualified or typedef) promote to double.
149  if (const BuiltinType *BT = Ty->getAsBuiltinType())
150    if (BT->getKind() == BuiltinType::Float)
151      return ImpCastExprToType(Expr, Context.DoubleTy);
152
153  UsualUnaryConversions(Expr);
154}
155
156// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
157// will warn if the resulting type is not a POD type.
158void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
159  DefaultArgumentPromotion(Expr);
160
161  if (!Expr->getType()->isPODType()) {
162    Diag(Expr->getLocStart(),
163         diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
164    Expr->getType() << CT;
165  }
166}
167
168
169/// UsualArithmeticConversions - Performs various conversions that are common to
170/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
171/// routine returns the first non-arithmetic type found. The client is
172/// responsible for emitting appropriate error diagnostics.
173/// FIXME: verify the conversion rules for "complex int" are consistent with
174/// GCC.
175QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
176                                          bool isCompAssign) {
177  if (!isCompAssign) {
178    UsualUnaryConversions(lhsExpr);
179    UsualUnaryConversions(rhsExpr);
180  }
181
182  // For conversion purposes, we ignore any qualifiers.
183  // For example, "const float" and "float" are equivalent.
184  QualType lhs =
185    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
186  QualType rhs =
187    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
188
189  // If both types are identical, no conversion is needed.
190  if (lhs == rhs)
191    return lhs;
192
193  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
194  // The caller can deal with this (e.g. pointer + int).
195  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
196    return lhs;
197
198  QualType destType = UsualArithmeticConversionsType(lhs, rhs);
199  if (!isCompAssign) {
200    ImpCastExprToType(lhsExpr, destType);
201    ImpCastExprToType(rhsExpr, destType);
202  }
203  return destType;
204}
205
206QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
207  // Perform the usual unary conversions. We do this early so that
208  // integral promotions to "int" can allow us to exit early, in the
209  // lhs == rhs check. Also, for conversion purposes, we ignore any
210  // qualifiers.  For example, "const float" and "float" are
211  // equivalent.
212  if (lhs->isPromotableIntegerType())
213    lhs = Context.IntTy;
214  else
215    lhs = lhs.getUnqualifiedType();
216  if (rhs->isPromotableIntegerType())
217    rhs = Context.IntTy;
218  else
219    rhs = rhs.getUnqualifiedType();
220
221  // If both types are identical, no conversion is needed.
222  if (lhs == rhs)
223    return lhs;
224
225  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
226  // The caller can deal with this (e.g. pointer + int).
227  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
228    return lhs;
229
230  // At this point, we have two different arithmetic types.
231
232  // Handle complex types first (C99 6.3.1.8p1).
233  if (lhs->isComplexType() || rhs->isComplexType()) {
234    // if we have an integer operand, the result is the complex type.
235    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
236      // convert the rhs to the lhs complex type.
237      return lhs;
238    }
239    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
240      // convert the lhs to the rhs complex type.
241      return rhs;
242    }
243    // This handles complex/complex, complex/float, or float/complex.
244    // When both operands are complex, the shorter operand is converted to the
245    // type of the longer, and that is the type of the result. This corresponds
246    // to what is done when combining two real floating-point operands.
247    // The fun begins when size promotion occur across type domains.
248    // From H&S 6.3.4: When one operand is complex and the other is a real
249    // floating-point type, the less precise type is converted, within it's
250    // real or complex domain, to the precision of the other type. For example,
251    // when combining a "long double" with a "double _Complex", the
252    // "double _Complex" is promoted to "long double _Complex".
253    int result = Context.getFloatingTypeOrder(lhs, rhs);
254
255    if (result > 0) { // The left side is bigger, convert rhs.
256      rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
257    } else if (result < 0) { // The right side is bigger, convert lhs.
258      lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
259    }
260    // At this point, lhs and rhs have the same rank/size. Now, make sure the
261    // domains match. This is a requirement for our implementation, C99
262    // does not require this promotion.
263    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
264      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
265        return rhs;
266      } else { // handle "_Complex double, double".
267        return lhs;
268      }
269    }
270    return lhs; // The domain/size match exactly.
271  }
272  // Now handle "real" floating types (i.e. float, double, long double).
273  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
274    // if we have an integer operand, the result is the real floating type.
275    if (rhs->isIntegerType()) {
276      // convert rhs to the lhs floating point type.
277      return lhs;
278    }
279    if (rhs->isComplexIntegerType()) {
280      // convert rhs to the complex floating point type.
281      return Context.getComplexType(lhs);
282    }
283    if (lhs->isIntegerType()) {
284      // convert lhs to the rhs floating point type.
285      return rhs;
286    }
287    if (lhs->isComplexIntegerType()) {
288      // convert lhs to the complex floating point type.
289      return Context.getComplexType(rhs);
290    }
291    // We have two real floating types, float/complex combos were handled above.
292    // Convert the smaller operand to the bigger result.
293    int result = Context.getFloatingTypeOrder(lhs, rhs);
294    if (result > 0) // convert the rhs
295      return lhs;
296    assert(result < 0 && "illegal float comparison");
297    return rhs;   // convert the lhs
298  }
299  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
300    // Handle GCC complex int extension.
301    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
302    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
303
304    if (lhsComplexInt && rhsComplexInt) {
305      if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
306                                      rhsComplexInt->getElementType()) >= 0)
307        return lhs; // convert the rhs
308      return rhs;
309    } else if (lhsComplexInt && rhs->isIntegerType()) {
310      // convert the rhs to the lhs complex type.
311      return lhs;
312    } else if (rhsComplexInt && lhs->isIntegerType()) {
313      // convert the lhs to the rhs complex type.
314      return rhs;
315    }
316  }
317  // Finally, we have two differing integer types.
318  // The rules for this case are in C99 6.3.1.8
319  int compare = Context.getIntegerTypeOrder(lhs, rhs);
320  bool lhsSigned = lhs->isSignedIntegerType(),
321       rhsSigned = rhs->isSignedIntegerType();
322  QualType destType;
323  if (lhsSigned == rhsSigned) {
324    // Same signedness; use the higher-ranked type
325    destType = compare >= 0 ? lhs : rhs;
326  } else if (compare != (lhsSigned ? 1 : -1)) {
327    // The unsigned type has greater than or equal rank to the
328    // signed type, so use the unsigned type
329    destType = lhsSigned ? rhs : lhs;
330  } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
331    // The two types are different widths; if we are here, that
332    // means the signed type is larger than the unsigned type, so
333    // use the signed type.
334    destType = lhsSigned ? lhs : rhs;
335  } else {
336    // The signed type is higher-ranked than the unsigned type,
337    // but isn't actually any bigger (like unsigned int and long
338    // on most 32-bit systems).  Use the unsigned type corresponding
339    // to the signed type.
340    destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
341  }
342  return destType;
343}
344
345//===----------------------------------------------------------------------===//
346//  Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
351/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens.  However, the common case is that StringToks points to one
354/// string.
355///
356Action::OwningExprResult
357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
358  assert(NumStringToks && "Must have at least one string!");
359
360  StringLiteralParser Literal(StringToks, NumStringToks, PP);
361  if (Literal.hadError)
362    return ExprError();
363
364  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
365  for (unsigned i = 0; i != NumStringToks; ++i)
366    StringTokLocs.push_back(StringToks[i].getLocation());
367
368  QualType StrTy = Context.CharTy;
369  if (Literal.AnyWide) StrTy = Context.getWCharType();
370  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
371
372  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
373  if (getLangOptions().CPlusPlus)
374    StrTy.addConst();
375
376  // Get an array type for the string, according to C99 6.4.5.  This includes
377  // the nul terminator character as well as the string length for pascal
378  // strings.
379  StrTy = Context.getConstantArrayType(StrTy,
380                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
381                                       ArrayType::Normal, 0);
382
383  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
384  return Owned(StringLiteral::Create(Context, Literal.GetString(),
385                                     Literal.GetStringLength(),
386                                     Literal.AnyWide, StrTy,
387                                     &StringTokLocs[0],
388                                     StringTokLocs.size()));
389}
390
391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
396/// FIXME: This will create BlockDeclRefExprs for global variables,
397/// function references, etc which is suboptimal :) and breaks
398/// things like "integer constant expression" tests.
399static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
400                                              ValueDecl *VD) {
401  // If the value is defined inside the block, we couldn't snapshot it even if
402  // we wanted to.
403  if (CurBlock->TheDecl == VD->getDeclContext())
404    return false;
405
406  // If this is an enum constant or function, it is constant, don't snapshot.
407  if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408    return false;
409
410  // If this is a reference to an extern, static, or global variable, no need to
411  // snapshot it.
412  // FIXME: What about 'const' variables in C++?
413  if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
414    return Var->hasLocalStorage();
415
416  return true;
417}
418
419
420
421/// ActOnIdentifierExpr - The parser read an identifier in expression context,
422/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
423/// identifier is used in a function call context.
424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
425/// class or namespace that the identifier must be a member of.
426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
427                                                 IdentifierInfo &II,
428                                                 bool HasTrailingLParen,
429                                                 const CXXScopeSpec *SS,
430                                                 bool isAddressOfOperand) {
431  return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
432                                  isAddressOfOperand);
433}
434
435/// BuildDeclRefExpr - Build either a DeclRefExpr or a
436/// QualifiedDeclRefExpr based on whether or not SS is a
437/// nested-name-specifier.
438DeclRefExpr *
439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
440                       bool TypeDependent, bool ValueDependent,
441                       const CXXScopeSpec *SS) {
442  if (SS && !SS->isEmpty())
443    return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
444                                              ValueDependent,
445                                              SS->getRange().getBegin());
446  else
447    return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
448}
449
450/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
451/// variable corresponding to the anonymous union or struct whose type
452/// is Record.
453static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
454  assert(Record->isAnonymousStructOrUnion() &&
455         "Record must be an anonymous struct or union!");
456
457  // FIXME: Once Decls are directly linked together, this will
458  // be an O(1) operation rather than a slow walk through DeclContext's
459  // vector (which itself will be eliminated). DeclGroups might make
460  // this even better.
461  DeclContext *Ctx = Record->getDeclContext();
462  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
463                               DEnd = Ctx->decls_end();
464       D != DEnd; ++D) {
465    if (*D == Record) {
466      // The object for the anonymous struct/union directly
467      // follows its type in the list of declarations.
468      ++D;
469      assert(D != DEnd && "Missing object for anonymous record");
470      assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
471      return *D;
472    }
473  }
474
475  assert(false && "Missing object for anonymous record");
476  return 0;
477}
478
479Sema::OwningExprResult
480Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
481                                               FieldDecl *Field,
482                                               Expr *BaseObjectExpr,
483                                               SourceLocation OpLoc) {
484  assert(Field->getDeclContext()->isRecord() &&
485         cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
486         && "Field must be stored inside an anonymous struct or union");
487
488  // Construct the sequence of field member references
489  // we'll have to perform to get to the field in the anonymous
490  // union/struct. The list of members is built from the field
491  // outward, so traverse it backwards to go from an object in
492  // the current context to the field we found.
493  llvm::SmallVector<FieldDecl *, 4> AnonFields;
494  AnonFields.push_back(Field);
495  VarDecl *BaseObject = 0;
496  DeclContext *Ctx = Field->getDeclContext();
497  do {
498    RecordDecl *Record = cast<RecordDecl>(Ctx);
499    Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
500    if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
501      AnonFields.push_back(AnonField);
502    else {
503      BaseObject = cast<VarDecl>(AnonObject);
504      break;
505    }
506    Ctx = Ctx->getParent();
507  } while (Ctx->isRecord() &&
508           cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
509
510  // Build the expression that refers to the base object, from
511  // which we will build a sequence of member references to each
512  // of the anonymous union objects and, eventually, the field we
513  // found via name lookup.
514  bool BaseObjectIsPointer = false;
515  unsigned ExtraQuals = 0;
516  if (BaseObject) {
517    // BaseObject is an anonymous struct/union variable (and is,
518    // therefore, not part of another non-anonymous record).
519    if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
520    BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
521                                               SourceLocation());
522    ExtraQuals
523      = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
524  } else if (BaseObjectExpr) {
525    // The caller provided the base object expression. Determine
526    // whether its a pointer and whether it adds any qualifiers to the
527    // anonymous struct/union fields we're looking into.
528    QualType ObjectType = BaseObjectExpr->getType();
529    if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
530      BaseObjectIsPointer = true;
531      ObjectType = ObjectPtr->getPointeeType();
532    }
533    ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
534  } else {
535    // We've found a member of an anonymous struct/union that is
536    // inside a non-anonymous struct/union, so in a well-formed
537    // program our base object expression is "this".
538    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
539      if (!MD->isStatic()) {
540        QualType AnonFieldType
541          = Context.getTagDeclType(
542                     cast<RecordDecl>(AnonFields.back()->getDeclContext()));
543        QualType ThisType = Context.getTagDeclType(MD->getParent());
544        if ((Context.getCanonicalType(AnonFieldType)
545               == Context.getCanonicalType(ThisType)) ||
546            IsDerivedFrom(ThisType, AnonFieldType)) {
547          // Our base object expression is "this".
548          BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
549                                                     MD->getThisType(Context));
550          BaseObjectIsPointer = true;
551        }
552      } else {
553        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
554          << Field->getDeclName());
555      }
556      ExtraQuals = MD->getTypeQualifiers();
557    }
558
559    if (!BaseObjectExpr)
560      return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
561        << Field->getDeclName());
562  }
563
564  // Build the implicit member references to the field of the
565  // anonymous struct/union.
566  Expr *Result = BaseObjectExpr;
567  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
568         FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
569       FI != FIEnd; ++FI) {
570    QualType MemberType = (*FI)->getType();
571    if (!(*FI)->isMutable()) {
572      unsigned combinedQualifiers
573        = MemberType.getCVRQualifiers() | ExtraQuals;
574      MemberType = MemberType.getQualifiedType(combinedQualifiers);
575    }
576    Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
577                                      OpLoc, MemberType);
578    BaseObjectIsPointer = false;
579    ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
580  }
581
582  return Owned(Result);
583}
584
585/// ActOnDeclarationNameExpr - The parser has read some kind of name
586/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
587/// performs lookup on that name and returns an expression that refers
588/// to that name. This routine isn't directly called from the parser,
589/// because the parser doesn't know about DeclarationName. Rather,
590/// this routine is called by ActOnIdentifierExpr,
591/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
592/// which form the DeclarationName from the corresponding syntactic
593/// forms.
594///
595/// HasTrailingLParen indicates whether this identifier is used in a
596/// function call context.  LookupCtx is only used for a C++
597/// qualified-id (foo::bar) to indicate the class or namespace that
598/// the identifier must be a member of.
599///
600/// isAddressOfOperand means that this expression is the direct operand
601/// of an address-of operator. This matters because this is the only
602/// situation where a qualified name referencing a non-static member may
603/// appear outside a member function of this class.
604Sema::OwningExprResult
605Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
606                               DeclarationName Name, bool HasTrailingLParen,
607                               const CXXScopeSpec *SS,
608                               bool isAddressOfOperand) {
609  // Could be enum-constant, value decl, instance variable, etc.
610  if (SS && SS->isInvalid())
611    return ExprError();
612  LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
613                                         false, true, Loc);
614
615  NamedDecl *D = 0;
616  if (Lookup.isAmbiguous()) {
617    DiagnoseAmbiguousLookup(Lookup, Name, Loc,
618                            SS && SS->isSet() ? SS->getRange()
619                                              : SourceRange());
620    return ExprError();
621  } else
622    D = Lookup.getAsDecl();
623
624  // If this reference is in an Objective-C method, then ivar lookup happens as
625  // well.
626  IdentifierInfo *II = Name.getAsIdentifierInfo();
627  if (II && getCurMethodDecl()) {
628    // There are two cases to handle here.  1) scoped lookup could have failed,
629    // in which case we should look for an ivar.  2) scoped lookup could have
630    // found a decl, but that decl is outside the current instance method (i.e.
631    // a global variable).  In these two cases, we do a lookup for an ivar with
632    // this name, if the lookup sucedes, we replace it our current decl.
633    if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
634      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
635      ObjCInterfaceDecl *ClassDeclared;
636      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
637        // Check if referencing a field with __attribute__((deprecated)).
638        if (DiagnoseUseOfDecl(IV, Loc))
639          return ExprError();
640        bool IsClsMethod = getCurMethodDecl()->isClassMethod();
641        // If a class method attemps to use a free standing ivar, this is
642        // an error.
643        if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
644           return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
645                           << IV->getDeclName());
646        // If a class method uses a global variable, even if an ivar with
647        // same name exists, use the global.
648        if (!IsClsMethod) {
649          if (IV->getAccessControl() == ObjCIvarDecl::Private &&
650              ClassDeclared != IFace)
651           Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
652          // FIXME: This should use a new expr for a direct reference, don't turn
653          // this into Self->ivar, just return a BareIVarExpr or something.
654          IdentifierInfo &II = Context.Idents.get("self");
655          OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
656          ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
657                                    Loc, static_cast<Expr*>(SelfExpr.release()),
658                                    true, true);
659          Context.setFieldDecl(IFace, IV, MRef);
660          return Owned(MRef);
661        }
662      }
663    }
664    else if (getCurMethodDecl()->isInstanceMethod()) {
665      // We should warn if a local variable hides an ivar.
666      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
667      ObjCInterfaceDecl *ClassDeclared;
668      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
669        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
670            IFace == ClassDeclared)
671          Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
672      }
673    }
674    // Needed to implement property "super.method" notation.
675    if (D == 0 && II->isStr("super")) {
676      QualType T;
677
678      if (getCurMethodDecl()->isInstanceMethod())
679        T = Context.getPointerType(Context.getObjCInterfaceType(
680                                   getCurMethodDecl()->getClassInterface()));
681      else
682        T = Context.getObjCClassType();
683      return Owned(new (Context) ObjCSuperExpr(Loc, T));
684    }
685  }
686
687  // Determine whether this name might be a candidate for
688  // argument-dependent lookup.
689  bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
690             HasTrailingLParen;
691
692  if (ADL && D == 0) {
693    // We've seen something of the form
694    //
695    //   identifier(
696    //
697    // and we did not find any entity by the name
698    // "identifier". However, this identifier is still subject to
699    // argument-dependent lookup, so keep track of the name.
700    return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
701                                                          Context.OverloadTy,
702                                                          Loc));
703  }
704
705  if (D == 0) {
706    // Otherwise, this could be an implicitly declared function reference (legal
707    // in C90, extension in C99).
708    if (HasTrailingLParen && II &&
709        !getLangOptions().CPlusPlus) // Not in C++.
710      D = ImplicitlyDefineFunction(Loc, *II, S);
711    else {
712      // If this name wasn't predeclared and if this is not a function call,
713      // diagnose the problem.
714      if (SS && !SS->isEmpty())
715        return ExprError(Diag(Loc, diag::err_typecheck_no_member)
716          << Name << SS->getRange());
717      else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
718               Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
719        return ExprError(Diag(Loc, diag::err_undeclared_use)
720          << Name.getAsString());
721      else
722        return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
723    }
724  }
725
726  // If this is an expression of the form &Class::member, don't build an
727  // implicit member ref, because we want a pointer to the member in general,
728  // not any specific instance's member.
729  if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
730    DeclContext *DC = getScopeRepAsDeclContext(*SS);
731    if (D && isa<CXXRecordDecl>(DC)) {
732      QualType DType;
733      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
734        DType = FD->getType().getNonReferenceType();
735      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
736        DType = Method->getType();
737      } else if (isa<OverloadedFunctionDecl>(D)) {
738        DType = Context.OverloadTy;
739      }
740      // Could be an inner type. That's diagnosed below, so ignore it here.
741      if (!DType.isNull()) {
742        // The pointer is type- and value-dependent if it points into something
743        // dependent.
744        bool Dependent = false;
745        for (; DC; DC = DC->getParent()) {
746          // FIXME: could stop early at namespace scope.
747          if (DC->isRecord()) {
748            CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
749            if (Context.getTypeDeclType(Record)->isDependentType()) {
750              Dependent = true;
751              break;
752            }
753          }
754        }
755        return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
756      }
757    }
758  }
759
760  // We may have found a field within an anonymous union or struct
761  // (C++ [class.union]).
762  if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
763    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
764      return BuildAnonymousStructUnionMemberReference(Loc, FD);
765
766  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
767    if (!MD->isStatic()) {
768      // C++ [class.mfct.nonstatic]p2:
769      //   [...] if name lookup (3.4.1) resolves the name in the
770      //   id-expression to a nonstatic nontype member of class X or of
771      //   a base class of X, the id-expression is transformed into a
772      //   class member access expression (5.2.5) using (*this) (9.3.2)
773      //   as the postfix-expression to the left of the '.' operator.
774      DeclContext *Ctx = 0;
775      QualType MemberType;
776      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
777        Ctx = FD->getDeclContext();
778        MemberType = FD->getType();
779
780        if (const ReferenceType *RefType = MemberType->getAsReferenceType())
781          MemberType = RefType->getPointeeType();
782        else if (!FD->isMutable()) {
783          unsigned combinedQualifiers
784            = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
785          MemberType = MemberType.getQualifiedType(combinedQualifiers);
786        }
787      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
788        if (!Method->isStatic()) {
789          Ctx = Method->getParent();
790          MemberType = Method->getType();
791        }
792      } else if (OverloadedFunctionDecl *Ovl
793                   = dyn_cast<OverloadedFunctionDecl>(D)) {
794        for (OverloadedFunctionDecl::function_iterator
795               Func = Ovl->function_begin(),
796               FuncEnd = Ovl->function_end();
797             Func != FuncEnd; ++Func) {
798          if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
799            if (!DMethod->isStatic()) {
800              Ctx = Ovl->getDeclContext();
801              MemberType = Context.OverloadTy;
802              break;
803            }
804        }
805      }
806
807      if (Ctx && Ctx->isRecord()) {
808        QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
809        QualType ThisType = Context.getTagDeclType(MD->getParent());
810        if ((Context.getCanonicalType(CtxType)
811               == Context.getCanonicalType(ThisType)) ||
812            IsDerivedFrom(ThisType, CtxType)) {
813          // Build the implicit member access expression.
814          Expr *This = new (Context) CXXThisExpr(SourceLocation(),
815                                                 MD->getThisType(Context));
816          return Owned(new (Context) MemberExpr(This, true, D,
817                                                SourceLocation(), MemberType));
818        }
819      }
820    }
821  }
822
823  if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
824    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
825      if (MD->isStatic())
826        // "invalid use of member 'x' in static member function"
827        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
828          << FD->getDeclName());
829    }
830
831    // Any other ways we could have found the field in a well-formed
832    // program would have been turned into implicit member expressions
833    // above.
834    return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
835      << FD->getDeclName());
836  }
837
838  if (isa<TypedefDecl>(D))
839    return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
840  if (isa<ObjCInterfaceDecl>(D))
841    return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
842  if (isa<NamespaceDecl>(D))
843    return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
844
845  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
846  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
847    return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
848                                  false, false, SS));
849  else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
850    return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
851                                  false, false, SS));
852  ValueDecl *VD = cast<ValueDecl>(D);
853
854  // Check whether this declaration can be used. Note that we suppress
855  // this check when we're going to perform argument-dependent lookup
856  // on this function name, because this might not be the function
857  // that overload resolution actually selects.
858  if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
859    return ExprError();
860
861  if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
862    // Warn about constructs like:
863    //   if (void *X = foo()) { ... } else { X }.
864    // In the else block, the pointer is always false.
865    if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
866      Scope *CheckS = S;
867      while (CheckS) {
868        if (CheckS->isWithinElse() &&
869            CheckS->getControlParent()->isDeclScope(Var)) {
870          if (Var->getType()->isBooleanType())
871            ExprError(Diag(Loc, diag::warn_value_always_false)
872              << Var->getDeclName());
873          else
874            ExprError(Diag(Loc, diag::warn_value_always_zero)
875              << Var->getDeclName());
876          break;
877        }
878
879        // Move up one more control parent to check again.
880        CheckS = CheckS->getControlParent();
881        if (CheckS)
882          CheckS = CheckS->getParent();
883      }
884    }
885  } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
886    if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
887      // C99 DR 316 says that, if a function type comes from a
888      // function definition (without a prototype), that type is only
889      // used for checking compatibility. Therefore, when referencing
890      // the function, we pretend that we don't have the full function
891      // type.
892      QualType T = Func->getType();
893      QualType NoProtoType = T;
894      if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
895        NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
896      return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
897    }
898  }
899
900  // Only create DeclRefExpr's for valid Decl's.
901  if (VD->isInvalidDecl())
902    return ExprError();
903
904  // If the identifier reference is inside a block, and it refers to a value
905  // that is outside the block, create a BlockDeclRefExpr instead of a
906  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
907  // the block is formed.
908  //
909  // We do not do this for things like enum constants, global variables, etc,
910  // as they do not get snapshotted.
911  //
912  if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
913    // Blocks that have these can't be constant.
914    CurBlock->hasBlockDeclRefExprs = true;
915
916    // The BlocksAttr indicates the variable is bound by-reference.
917    if (VD->getAttr<BlocksAttr>())
918      return Owned(new (Context) BlockDeclRefExpr(VD,
919                               VD->getType().getNonReferenceType(), Loc, true));
920
921    // Variable will be bound by-copy, make it const within the closure.
922    VD->getType().addConst();
923    return Owned(new (Context) BlockDeclRefExpr(VD,
924                             VD->getType().getNonReferenceType(), Loc, false));
925  }
926  // If this reference is not in a block or if the referenced variable is
927  // within the block, create a normal DeclRefExpr.
928
929  bool TypeDependent = false;
930  bool ValueDependent = false;
931  if (getLangOptions().CPlusPlus) {
932    // C++ [temp.dep.expr]p3:
933    //   An id-expression is type-dependent if it contains:
934    //     - an identifier that was declared with a dependent type,
935    if (VD->getType()->isDependentType())
936      TypeDependent = true;
937    //     - FIXME: a template-id that is dependent,
938    //     - a conversion-function-id that specifies a dependent type,
939    else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
940             Name.getCXXNameType()->isDependentType())
941      TypeDependent = true;
942    //     - a nested-name-specifier that contains a class-name that
943    //       names a dependent type.
944    else if (SS && !SS->isEmpty()) {
945      for (DeclContext *DC = getScopeRepAsDeclContext(*SS);
946           DC; DC = DC->getParent()) {
947        // FIXME: could stop early at namespace scope.
948        if (DC->isRecord()) {
949          CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
950          if (Context.getTypeDeclType(Record)->isDependentType()) {
951            TypeDependent = true;
952            break;
953          }
954        }
955      }
956    }
957
958    // C++ [temp.dep.constexpr]p2:
959    //
960    //   An identifier is value-dependent if it is:
961    //     - a name declared with a dependent type,
962    if (TypeDependent)
963      ValueDependent = true;
964    //     - the name of a non-type template parameter,
965    else if (isa<NonTypeTemplateParmDecl>(VD))
966      ValueDependent = true;
967    //    - a constant with integral or enumeration type and is
968    //      initialized with an expression that is value-dependent
969    //      (FIXME!).
970  }
971
972  return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
973                                TypeDependent, ValueDependent, SS));
974}
975
976Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
977                                                 tok::TokenKind Kind) {
978  PredefinedExpr::IdentType IT;
979
980  switch (Kind) {
981  default: assert(0 && "Unknown simple primary expr!");
982  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
983  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
984  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
985  }
986
987  // Pre-defined identifiers are of type char[x], where x is the length of the
988  // string.
989  unsigned Length;
990  if (FunctionDecl *FD = getCurFunctionDecl())
991    Length = FD->getIdentifier()->getLength();
992  else if (ObjCMethodDecl *MD = getCurMethodDecl())
993    Length = MD->getSynthesizedMethodSize();
994  else {
995    Diag(Loc, diag::ext_predef_outside_function);
996    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
997    Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
998  }
999
1000
1001  llvm::APInt LengthI(32, Length + 1);
1002  QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
1003  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1004  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1005}
1006
1007Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1008  llvm::SmallString<16> CharBuffer;
1009  CharBuffer.resize(Tok.getLength());
1010  const char *ThisTokBegin = &CharBuffer[0];
1011  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1012
1013  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1014                            Tok.getLocation(), PP);
1015  if (Literal.hadError())
1016    return ExprError();
1017
1018  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1019
1020  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1021                                              Literal.isWide(),
1022                                              type, Tok.getLocation()));
1023}
1024
1025Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1026  // Fast path for a single digit (which is quite common).  A single digit
1027  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1028  if (Tok.getLength() == 1) {
1029    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1030    unsigned IntSize = Context.Target.getIntWidth();
1031    return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1032                    Context.IntTy, Tok.getLocation()));
1033  }
1034
1035  llvm::SmallString<512> IntegerBuffer;
1036  // Add padding so that NumericLiteralParser can overread by one character.
1037  IntegerBuffer.resize(Tok.getLength()+1);
1038  const char *ThisTokBegin = &IntegerBuffer[0];
1039
1040  // Get the spelling of the token, which eliminates trigraphs, etc.
1041  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1042
1043  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1044                               Tok.getLocation(), PP);
1045  if (Literal.hadError)
1046    return ExprError();
1047
1048  Expr *Res;
1049
1050  if (Literal.isFloatingLiteral()) {
1051    QualType Ty;
1052    if (Literal.isFloat)
1053      Ty = Context.FloatTy;
1054    else if (!Literal.isLong)
1055      Ty = Context.DoubleTy;
1056    else
1057      Ty = Context.LongDoubleTy;
1058
1059    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1060
1061    // isExact will be set by GetFloatValue().
1062    bool isExact = false;
1063    Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1064                                        &isExact, Ty, Tok.getLocation());
1065
1066  } else if (!Literal.isIntegerLiteral()) {
1067    return ExprError();
1068  } else {
1069    QualType Ty;
1070
1071    // long long is a C99 feature.
1072    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1073        Literal.isLongLong)
1074      Diag(Tok.getLocation(), diag::ext_longlong);
1075
1076    // Get the value in the widest-possible width.
1077    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1078
1079    if (Literal.GetIntegerValue(ResultVal)) {
1080      // If this value didn't fit into uintmax_t, warn and force to ull.
1081      Diag(Tok.getLocation(), diag::warn_integer_too_large);
1082      Ty = Context.UnsignedLongLongTy;
1083      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1084             "long long is not intmax_t?");
1085    } else {
1086      // If this value fits into a ULL, try to figure out what else it fits into
1087      // according to the rules of C99 6.4.4.1p5.
1088
1089      // Octal, Hexadecimal, and integers with a U suffix are allowed to
1090      // be an unsigned int.
1091      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1092
1093      // Check from smallest to largest, picking the smallest type we can.
1094      unsigned Width = 0;
1095      if (!Literal.isLong && !Literal.isLongLong) {
1096        // Are int/unsigned possibilities?
1097        unsigned IntSize = Context.Target.getIntWidth();
1098
1099        // Does it fit in a unsigned int?
1100        if (ResultVal.isIntN(IntSize)) {
1101          // Does it fit in a signed int?
1102          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1103            Ty = Context.IntTy;
1104          else if (AllowUnsigned)
1105            Ty = Context.UnsignedIntTy;
1106          Width = IntSize;
1107        }
1108      }
1109
1110      // Are long/unsigned long possibilities?
1111      if (Ty.isNull() && !Literal.isLongLong) {
1112        unsigned LongSize = Context.Target.getLongWidth();
1113
1114        // Does it fit in a unsigned long?
1115        if (ResultVal.isIntN(LongSize)) {
1116          // Does it fit in a signed long?
1117          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1118            Ty = Context.LongTy;
1119          else if (AllowUnsigned)
1120            Ty = Context.UnsignedLongTy;
1121          Width = LongSize;
1122        }
1123      }
1124
1125      // Finally, check long long if needed.
1126      if (Ty.isNull()) {
1127        unsigned LongLongSize = Context.Target.getLongLongWidth();
1128
1129        // Does it fit in a unsigned long long?
1130        if (ResultVal.isIntN(LongLongSize)) {
1131          // Does it fit in a signed long long?
1132          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1133            Ty = Context.LongLongTy;
1134          else if (AllowUnsigned)
1135            Ty = Context.UnsignedLongLongTy;
1136          Width = LongLongSize;
1137        }
1138      }
1139
1140      // If we still couldn't decide a type, we probably have something that
1141      // does not fit in a signed long long, but has no U suffix.
1142      if (Ty.isNull()) {
1143        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1144        Ty = Context.UnsignedLongLongTy;
1145        Width = Context.Target.getLongLongWidth();
1146      }
1147
1148      if (ResultVal.getBitWidth() != Width)
1149        ResultVal.trunc(Width);
1150    }
1151    Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1152  }
1153
1154  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1155  if (Literal.isImaginary)
1156    Res = new (Context) ImaginaryLiteral(Res,
1157                                        Context.getComplexType(Res->getType()));
1158
1159  return Owned(Res);
1160}
1161
1162Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1163                                              SourceLocation R, ExprArg Val) {
1164  Expr *E = (Expr *)Val.release();
1165  assert((E != 0) && "ActOnParenExpr() missing expr");
1166  return Owned(new (Context) ParenExpr(L, R, E));
1167}
1168
1169/// The UsualUnaryConversions() function is *not* called by this routine.
1170/// See C99 6.3.2.1p[2-4] for more details.
1171bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1172                                     SourceLocation OpLoc,
1173                                     const SourceRange &ExprRange,
1174                                     bool isSizeof) {
1175  if (exprType->isDependentType())
1176    return false;
1177
1178  // C99 6.5.3.4p1:
1179  if (isa<FunctionType>(exprType)) {
1180    // alignof(function) is allowed.
1181    if (isSizeof)
1182      Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1183    return false;
1184  }
1185
1186  if (exprType->isVoidType()) {
1187    Diag(OpLoc, diag::ext_sizeof_void_type)
1188      << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1189    return false;
1190  }
1191
1192  return RequireCompleteType(OpLoc, exprType,
1193                                isSizeof ? diag::err_sizeof_incomplete_type :
1194                                           diag::err_alignof_incomplete_type,
1195                                ExprRange);
1196}
1197
1198bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1199                            const SourceRange &ExprRange) {
1200  E = E->IgnoreParens();
1201
1202  // alignof decl is always ok.
1203  if (isa<DeclRefExpr>(E))
1204    return false;
1205
1206  // Cannot know anything else if the expression is dependent.
1207  if (E->isTypeDependent())
1208    return false;
1209
1210  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1211    if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1212      if (FD->isBitField()) {
1213        Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1214        return true;
1215      }
1216      // Other fields are ok.
1217      return false;
1218    }
1219  }
1220  return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1221}
1222
1223/// \brief Build a sizeof or alignof expression given a type operand.
1224Action::OwningExprResult
1225Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1226                              bool isSizeOf, SourceRange R) {
1227  if (T.isNull())
1228    return ExprError();
1229
1230  if (!T->isDependentType() &&
1231      CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1232    return ExprError();
1233
1234  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1235  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1236                                               Context.getSizeType(), OpLoc,
1237                                               R.getEnd()));
1238}
1239
1240/// \brief Build a sizeof or alignof expression given an expression
1241/// operand.
1242Action::OwningExprResult
1243Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1244                              bool isSizeOf, SourceRange R) {
1245  // Verify that the operand is valid.
1246  bool isInvalid = false;
1247  if (E->isTypeDependent()) {
1248    // Delay type-checking for type-dependent expressions.
1249  } else if (!isSizeOf) {
1250    isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1251  } else if (E->isBitField()) {  // C99 6.5.3.4p1.
1252    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1253    isInvalid = true;
1254  } else {
1255    isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1256  }
1257
1258  if (isInvalid)
1259    return ExprError();
1260
1261  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1262  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1263                                               Context.getSizeType(), OpLoc,
1264                                               R.getEnd()));
1265}
1266
1267/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1268/// the same for @c alignof and @c __alignof
1269/// Note that the ArgRange is invalid if isType is false.
1270Action::OwningExprResult
1271Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1272                             void *TyOrEx, const SourceRange &ArgRange) {
1273  // If error parsing type, ignore.
1274  if (TyOrEx == 0) return ExprError();
1275
1276  if (isType) {
1277    QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1278    return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1279  }
1280
1281  // Get the end location.
1282  Expr *ArgEx = (Expr *)TyOrEx;
1283  Action::OwningExprResult Result
1284    = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1285
1286  if (Result.isInvalid())
1287    DeleteExpr(ArgEx);
1288
1289  return move(Result);
1290}
1291
1292QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
1293  if (V->isTypeDependent())
1294    return Context.DependentTy;
1295
1296  DefaultFunctionArrayConversion(V);
1297
1298  // These operators return the element type of a complex type.
1299  if (const ComplexType *CT = V->getType()->getAsComplexType())
1300    return CT->getElementType();
1301
1302  // Otherwise they pass through real integer and floating point types here.
1303  if (V->getType()->isArithmeticType())
1304    return V->getType();
1305
1306  // Reject anything else.
1307  Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1308    << (isReal ? "__real" : "__imag");
1309  return QualType();
1310}
1311
1312
1313
1314Action::OwningExprResult
1315Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1316                          tok::TokenKind Kind, ExprArg Input) {
1317  Expr *Arg = (Expr *)Input.get();
1318
1319  UnaryOperator::Opcode Opc;
1320  switch (Kind) {
1321  default: assert(0 && "Unknown unary op!");
1322  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
1323  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1324  }
1325
1326  if (getLangOptions().CPlusPlus &&
1327      (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1328    // Which overloaded operator?
1329    OverloadedOperatorKind OverOp =
1330      (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1331
1332    // C++ [over.inc]p1:
1333    //
1334    //     [...] If the function is a member function with one
1335    //     parameter (which shall be of type int) or a non-member
1336    //     function with two parameters (the second of which shall be
1337    //     of type int), it defines the postfix increment operator ++
1338    //     for objects of that type. When the postfix increment is
1339    //     called as a result of using the ++ operator, the int
1340    //     argument will have value zero.
1341    Expr *Args[2] = {
1342      Arg,
1343      new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1344                          /*isSigned=*/true), Context.IntTy, SourceLocation())
1345    };
1346
1347    // Build the candidate set for overloading
1348    OverloadCandidateSet CandidateSet;
1349    AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
1350
1351    // Perform overload resolution.
1352    OverloadCandidateSet::iterator Best;
1353    switch (BestViableFunction(CandidateSet, Best)) {
1354    case OR_Success: {
1355      // We found a built-in operator or an overloaded operator.
1356      FunctionDecl *FnDecl = Best->Function;
1357
1358      if (FnDecl) {
1359        // We matched an overloaded operator. Build a call to that
1360        // operator.
1361
1362        // Convert the arguments.
1363        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1364          if (PerformObjectArgumentInitialization(Arg, Method))
1365            return ExprError();
1366        } else {
1367          // Convert the arguments.
1368          if (PerformCopyInitialization(Arg,
1369                                        FnDecl->getParamDecl(0)->getType(),
1370                                        "passing"))
1371            return ExprError();
1372        }
1373
1374        // Determine the result type
1375        QualType ResultTy
1376          = FnDecl->getType()->getAsFunctionType()->getResultType();
1377        ResultTy = ResultTy.getNonReferenceType();
1378
1379        // Build the actual expression node.
1380        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1381                                                 SourceLocation());
1382        UsualUnaryConversions(FnExpr);
1383
1384        Input.release();
1385        return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1386                                                       Args, 2, ResultTy,
1387                                                       OpLoc));
1388      } else {
1389        // We matched a built-in operator. Convert the arguments, then
1390        // break out so that we will build the appropriate built-in
1391        // operator node.
1392        if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1393                                      "passing"))
1394          return ExprError();
1395
1396        break;
1397      }
1398    }
1399
1400    case OR_No_Viable_Function:
1401      // No viable function; fall through to handling this as a
1402      // built-in operator, which will produce an error message for us.
1403      break;
1404
1405    case OR_Ambiguous:
1406      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
1407          << UnaryOperator::getOpcodeStr(Opc)
1408          << Arg->getSourceRange();
1409      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1410      return ExprError();
1411
1412    case OR_Deleted:
1413      Diag(OpLoc, diag::err_ovl_deleted_oper)
1414        << Best->Function->isDeleted()
1415        << UnaryOperator::getOpcodeStr(Opc)
1416        << Arg->getSourceRange();
1417      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1418      return ExprError();
1419    }
1420
1421    // Either we found no viable overloaded operator or we matched a
1422    // built-in operator. In either case, fall through to trying to
1423    // build a built-in operation.
1424  }
1425
1426  QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1427                                                 Opc == UnaryOperator::PostInc);
1428  if (result.isNull())
1429    return ExprError();
1430  Input.release();
1431  return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
1432}
1433
1434Action::OwningExprResult
1435Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1436                              ExprArg Idx, SourceLocation RLoc) {
1437  Expr *LHSExp = static_cast<Expr*>(Base.get()),
1438       *RHSExp = static_cast<Expr*>(Idx.get());
1439
1440  if (getLangOptions().CPlusPlus &&
1441      (LHSExp->getType()->isRecordType() ||
1442       LHSExp->getType()->isEnumeralType() ||
1443       RHSExp->getType()->isRecordType() ||
1444       RHSExp->getType()->isEnumeralType())) {
1445    // Add the appropriate overloaded operators (C++ [over.match.oper])
1446    // to the candidate set.
1447    OverloadCandidateSet CandidateSet;
1448    Expr *Args[2] = { LHSExp, RHSExp };
1449    AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1450                          SourceRange(LLoc, RLoc));
1451
1452    // Perform overload resolution.
1453    OverloadCandidateSet::iterator Best;
1454    switch (BestViableFunction(CandidateSet, Best)) {
1455    case OR_Success: {
1456      // We found a built-in operator or an overloaded operator.
1457      FunctionDecl *FnDecl = Best->Function;
1458
1459      if (FnDecl) {
1460        // We matched an overloaded operator. Build a call to that
1461        // operator.
1462
1463        // Convert the arguments.
1464        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1465          if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1466              PerformCopyInitialization(RHSExp,
1467                                        FnDecl->getParamDecl(0)->getType(),
1468                                        "passing"))
1469            return ExprError();
1470        } else {
1471          // Convert the arguments.
1472          if (PerformCopyInitialization(LHSExp,
1473                                        FnDecl->getParamDecl(0)->getType(),
1474                                        "passing") ||
1475              PerformCopyInitialization(RHSExp,
1476                                        FnDecl->getParamDecl(1)->getType(),
1477                                        "passing"))
1478            return ExprError();
1479        }
1480
1481        // Determine the result type
1482        QualType ResultTy
1483          = FnDecl->getType()->getAsFunctionType()->getResultType();
1484        ResultTy = ResultTy.getNonReferenceType();
1485
1486        // Build the actual expression node.
1487        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1488                                                 SourceLocation());
1489        UsualUnaryConversions(FnExpr);
1490
1491        Base.release();
1492        Idx.release();
1493        return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1494                                                       FnExpr, Args, 2,
1495                                                       ResultTy, LLoc));
1496      } else {
1497        // We matched a built-in operator. Convert the arguments, then
1498        // break out so that we will build the appropriate built-in
1499        // operator node.
1500        if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1501                                      "passing") ||
1502            PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1503                                      "passing"))
1504          return ExprError();
1505
1506        break;
1507      }
1508    }
1509
1510    case OR_No_Viable_Function:
1511      // No viable function; fall through to handling this as a
1512      // built-in operator, which will produce an error message for us.
1513      break;
1514
1515    case OR_Ambiguous:
1516      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
1517          << "[]"
1518          << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1519      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1520      return ExprError();
1521
1522    case OR_Deleted:
1523      Diag(LLoc, diag::err_ovl_deleted_oper)
1524        << Best->Function->isDeleted()
1525        << "[]"
1526        << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1527      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1528      return ExprError();
1529    }
1530
1531    // Either we found no viable overloaded operator or we matched a
1532    // built-in operator. In either case, fall through to trying to
1533    // build a built-in operation.
1534  }
1535
1536  // Perform default conversions.
1537  DefaultFunctionArrayConversion(LHSExp);
1538  DefaultFunctionArrayConversion(RHSExp);
1539
1540  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1541
1542  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1543  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1544  // in the subscript position. As a result, we need to derive the array base
1545  // and index from the expression types.
1546  Expr *BaseExpr, *IndexExpr;
1547  QualType ResultType;
1548  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1549    BaseExpr = LHSExp;
1550    IndexExpr = RHSExp;
1551    ResultType = Context.DependentTy;
1552  } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
1553    BaseExpr = LHSExp;
1554    IndexExpr = RHSExp;
1555    // FIXME: need to deal with const...
1556    ResultType = PTy->getPointeeType();
1557  } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
1558     // Handle the uncommon case of "123[Ptr]".
1559    BaseExpr = RHSExp;
1560    IndexExpr = LHSExp;
1561    // FIXME: need to deal with const...
1562    ResultType = PTy->getPointeeType();
1563  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1564    BaseExpr = LHSExp;    // vectors: V[123]
1565    IndexExpr = RHSExp;
1566
1567    // FIXME: need to deal with const...
1568    ResultType = VTy->getElementType();
1569  } else {
1570    return ExprError(Diag(LHSExp->getLocStart(),
1571      diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1572  }
1573  // C99 6.5.2.1p1
1574  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
1575    return ExprError(Diag(IndexExpr->getLocStart(),
1576      diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
1577
1578  // C99 6.5.2.1p1: "shall have type "pointer to *object* type".  In practice,
1579  // the following check catches trying to index a pointer to a function (e.g.
1580  // void (*)(int)) and pointers to incomplete types.  Functions are not
1581  // objects in C99.
1582  if (!ResultType->isObjectType() && !ResultType->isDependentType())
1583    return ExprError(Diag(BaseExpr->getLocStart(),
1584                diag::err_typecheck_subscript_not_object)
1585      << BaseExpr->getType() << BaseExpr->getSourceRange());
1586
1587  Base.release();
1588  Idx.release();
1589  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1590                                                ResultType, RLoc));
1591}
1592
1593QualType Sema::
1594CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1595                        IdentifierInfo &CompName, SourceLocation CompLoc) {
1596  const ExtVectorType *vecType = baseType->getAsExtVectorType();
1597
1598  // The vector accessor can't exceed the number of elements.
1599  const char *compStr = CompName.getName();
1600
1601  // This flag determines whether or not the component is one of the four
1602  // special names that indicate a subset of exactly half the elements are
1603  // to be selected.
1604  bool HalvingSwizzle = false;
1605
1606  // This flag determines whether or not CompName has an 's' char prefix,
1607  // indicating that it is a string of hex values to be used as vector indices.
1608  bool HexSwizzle = *compStr == 's';
1609
1610  // Check that we've found one of the special components, or that the component
1611  // names must come from the same set.
1612  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1613      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1614    HalvingSwizzle = true;
1615  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1616    do
1617      compStr++;
1618    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1619  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1620    do
1621      compStr++;
1622    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1623  }
1624
1625  if (!HalvingSwizzle && *compStr) {
1626    // We didn't get to the end of the string. This means the component names
1627    // didn't come from the same set *or* we encountered an illegal name.
1628    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1629      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1630    return QualType();
1631  }
1632
1633  // Ensure no component accessor exceeds the width of the vector type it
1634  // operates on.
1635  if (!HalvingSwizzle) {
1636    compStr = CompName.getName();
1637
1638    if (HexSwizzle)
1639      compStr++;
1640
1641    while (*compStr) {
1642      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1643        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1644          << baseType << SourceRange(CompLoc);
1645        return QualType();
1646      }
1647    }
1648  }
1649
1650  // If this is a halving swizzle, verify that the base type has an even
1651  // number of elements.
1652  if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1653    Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1654      << baseType << SourceRange(CompLoc);
1655    return QualType();
1656  }
1657
1658  // The component accessor looks fine - now we need to compute the actual type.
1659  // The vector type is implied by the component accessor. For example,
1660  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1661  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1662  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1663  unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1664                                     : CompName.getLength();
1665  if (HexSwizzle)
1666    CompSize--;
1667
1668  if (CompSize == 1)
1669    return vecType->getElementType();
1670
1671  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1672  // Now look up the TypeDefDecl from the vector type. Without this,
1673  // diagostics look bad. We want extended vector types to appear built-in.
1674  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1675    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1676      return Context.getTypedefType(ExtVectorDecls[i]);
1677  }
1678  return VT; // should never get here (a typedef type should always be found).
1679}
1680
1681
1682Action::OwningExprResult
1683Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1684                               tok::TokenKind OpKind, SourceLocation MemberLoc,
1685                               IdentifierInfo &Member,
1686                               DeclTy *ObjCImpDecl) {
1687  Expr *BaseExpr = static_cast<Expr *>(Base.release());
1688  assert(BaseExpr && "no record expression");
1689
1690  // Perform default conversions.
1691  DefaultFunctionArrayConversion(BaseExpr);
1692
1693  QualType BaseType = BaseExpr->getType();
1694  assert(!BaseType.isNull() && "no type for member expression");
1695
1696  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
1697  // must have pointer type, and the accessed type is the pointee.
1698  if (OpKind == tok::arrow) {
1699    if (const PointerType *PT = BaseType->getAsPointerType())
1700      BaseType = PT->getPointeeType();
1701    else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1702      return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1703                                            MemberLoc, Member));
1704    else
1705      return ExprError(Diag(MemberLoc,
1706                            diag::err_typecheck_member_reference_arrow)
1707        << BaseType << BaseExpr->getSourceRange());
1708  }
1709
1710  // Handle field access to simple records.  This also handles access to fields
1711  // of the ObjC 'id' struct.
1712  if (const RecordType *RTy = BaseType->getAsRecordType()) {
1713    RecordDecl *RDecl = RTy->getDecl();
1714    if (RequireCompleteType(OpLoc, BaseType,
1715                               diag::err_typecheck_incomplete_tag,
1716                               BaseExpr->getSourceRange()))
1717      return ExprError();
1718
1719    // The record definition is complete, now make sure the member is valid.
1720    // FIXME: Qualified name lookup for C++ is a bit more complicated
1721    // than this.
1722    LookupResult Result
1723      = LookupQualifiedName(RDecl, DeclarationName(&Member),
1724                            LookupMemberName, false);
1725
1726    NamedDecl *MemberDecl = 0;
1727    if (!Result)
1728      return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1729               << &Member << BaseExpr->getSourceRange());
1730    else if (Result.isAmbiguous()) {
1731      DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1732                              MemberLoc, BaseExpr->getSourceRange());
1733      return ExprError();
1734    } else
1735      MemberDecl = Result;
1736
1737    // If the decl being referenced had an error, return an error for this
1738    // sub-expr without emitting another error, in order to avoid cascading
1739    // error cases.
1740    if (MemberDecl->isInvalidDecl())
1741      return ExprError();
1742
1743    // Check the use of this field
1744    if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1745      return ExprError();
1746
1747    if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
1748      // We may have found a field within an anonymous union or struct
1749      // (C++ [class.union]).
1750      if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1751        return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1752                                                        BaseExpr, OpLoc);
1753
1754      // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1755      // FIXME: Handle address space modifiers
1756      QualType MemberType = FD->getType();
1757      if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1758        MemberType = Ref->getPointeeType();
1759      else {
1760        unsigned combinedQualifiers =
1761          MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
1762        if (FD->isMutable())
1763          combinedQualifiers &= ~QualType::Const;
1764        MemberType = MemberType.getQualifiedType(combinedQualifiers);
1765      }
1766
1767      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1768                                            MemberLoc, MemberType));
1769    } else if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
1770      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1771                                  Var, MemberLoc,
1772                                  Var->getType().getNonReferenceType()));
1773    else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
1774      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1775                                  MemberFn, MemberLoc, MemberFn->getType()));
1776    else if (OverloadedFunctionDecl *Ovl
1777             = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
1778      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
1779                                  MemberLoc, Context.OverloadTy));
1780    else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
1781      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1782                                            Enum, MemberLoc, Enum->getType()));
1783    else if (isa<TypeDecl>(MemberDecl))
1784      return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1785        << DeclarationName(&Member) << int(OpKind == tok::arrow));
1786
1787    // We found a declaration kind that we didn't expect. This is a
1788    // generic error message that tells the user that she can't refer
1789    // to this member with '.' or '->'.
1790    return ExprError(Diag(MemberLoc,
1791                          diag::err_typecheck_member_reference_unknown)
1792      << DeclarationName(&Member) << int(OpKind == tok::arrow));
1793  }
1794
1795  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1796  // (*Obj).ivar.
1797  if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1798    ObjCInterfaceDecl *ClassDeclared;
1799    if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1800                                                             ClassDeclared)) {
1801      // If the decl being referenced had an error, return an error for this
1802      // sub-expr without emitting another error, in order to avoid cascading
1803      // error cases.
1804      if (IV->isInvalidDecl())
1805        return ExprError();
1806
1807      // Check whether we can reference this field.
1808      if (DiagnoseUseOfDecl(IV, MemberLoc))
1809        return ExprError();
1810      if (IV->getAccessControl() != ObjCIvarDecl::Public) {
1811        ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1812        if (ObjCMethodDecl *MD = getCurMethodDecl())
1813          ClassOfMethodDecl =  MD->getClassInterface();
1814        else if (ObjCImpDecl && getCurFunctionDecl()) {
1815          // Case of a c-function declared inside an objc implementation.
1816          // FIXME: For a c-style function nested inside an objc implementation
1817          // class, there is no implementation context available, so we pass down
1818          // the context as argument to this routine. Ideally, this context need
1819          // be passed down in the AST node and somehow calculated from the AST
1820          // for a function decl.
1821          Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl);
1822          if (ObjCImplementationDecl *IMPD =
1823              dyn_cast<ObjCImplementationDecl>(ImplDecl))
1824            ClassOfMethodDecl = IMPD->getClassInterface();
1825          else if (ObjCCategoryImplDecl* CatImplClass =
1826                      dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1827            ClassOfMethodDecl = CatImplClass->getClassInterface();
1828        }
1829        if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1830          if (ClassDeclared != IFTy->getDecl() ||
1831              ClassOfMethodDecl != ClassDeclared)
1832            Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1833        }
1834        // @protected
1835        else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1836          Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1837      }
1838
1839      ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1840                                                 MemberLoc, BaseExpr,
1841                                                 OpKind == tok::arrow);
1842      Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1843      return Owned(MRef);
1844    }
1845    return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1846                       << IFTy->getDecl()->getDeclName() << &Member
1847                       << BaseExpr->getSourceRange());
1848  }
1849
1850  // Handle Objective-C property access, which is "Obj.property" where Obj is a
1851  // pointer to a (potentially qualified) interface type.
1852  const PointerType *PTy;
1853  const ObjCInterfaceType *IFTy;
1854  if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1855      (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1856    ObjCInterfaceDecl *IFace = IFTy->getDecl();
1857
1858    // Search for a declared property first.
1859    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
1860      // Check whether we can reference this property.
1861      if (DiagnoseUseOfDecl(PD, MemberLoc))
1862        return ExprError();
1863
1864      return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1865                                                     MemberLoc, BaseExpr));
1866    }
1867
1868    // Check protocols on qualified interfaces.
1869    for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1870         E = IFTy->qual_end(); I != E; ++I)
1871      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1872        // Check whether we can reference this property.
1873        if (DiagnoseUseOfDecl(PD, MemberLoc))
1874          return ExprError();
1875
1876        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1877                                                       MemberLoc, BaseExpr));
1878      }
1879
1880    // If that failed, look for an "implicit" property by seeing if the nullary
1881    // selector is implemented.
1882
1883    // FIXME: The logic for looking up nullary and unary selectors should be
1884    // shared with the code in ActOnInstanceMessage.
1885
1886    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1887    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1888
1889    // If this reference is in an @implementation, check for 'private' methods.
1890    if (!Getter)
1891      if (ObjCImplementationDecl *ImpDecl =
1892          ObjCImplementations[IFace->getIdentifier()])
1893        Getter = ImpDecl->getInstanceMethod(Sel);
1894
1895    // Look through local category implementations associated with the class.
1896    if (!Getter) {
1897      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1898        if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1899          Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1900      }
1901    }
1902    if (Getter) {
1903      // Check if we can reference this property.
1904      if (DiagnoseUseOfDecl(Getter, MemberLoc))
1905        return ExprError();
1906    }
1907    // If we found a getter then this may be a valid dot-reference, we
1908    // will look for the matching setter, in case it is needed.
1909    Selector SetterSel =
1910      SelectorTable::constructSetterName(PP.getIdentifierTable(),
1911                                         PP.getSelectorTable(), &Member);
1912    ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1913    if (!Setter) {
1914      // If this reference is in an @implementation, also check for 'private'
1915      // methods.
1916      if (ObjCImplementationDecl *ImpDecl =
1917          ObjCImplementations[IFace->getIdentifier()])
1918        Setter = ImpDecl->getInstanceMethod(SetterSel);
1919    }
1920    // Look through local category implementations associated with the class.
1921    if (!Setter) {
1922      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1923        if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1924          Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1925      }
1926    }
1927
1928    if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1929      return ExprError();
1930
1931    if (Getter || Setter) {
1932      QualType PType;
1933
1934      if (Getter)
1935        PType = Getter->getResultType();
1936      else {
1937        for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
1938             E = Setter->param_end(); PI != E; ++PI)
1939          PType = (*PI)->getType();
1940      }
1941      // FIXME: we must check that the setter has property type.
1942      return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
1943                                      Setter, MemberLoc, BaseExpr));
1944    }
1945    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1946      << &Member << BaseType);
1947  }
1948  // Handle properties on qualified "id" protocols.
1949  const ObjCQualifiedIdType *QIdTy;
1950  if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1951    // Check protocols on qualified interfaces.
1952    for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1953         E = QIdTy->qual_end(); I != E; ++I) {
1954      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1955        // Check the use of this declaration
1956        if (DiagnoseUseOfDecl(PD, MemberLoc))
1957          return ExprError();
1958
1959        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1960                                                       MemberLoc, BaseExpr));
1961      }
1962      // Also must look for a getter name which uses property syntax.
1963      Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1964      if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1965        // Check the use of this method.
1966        if (DiagnoseUseOfDecl(OMD, MemberLoc))
1967          return ExprError();
1968
1969        return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1970                        OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
1971      }
1972    }
1973
1974    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1975                       << &Member << BaseType);
1976  }
1977  // Handle properties on ObjC 'Class' types.
1978  if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
1979    // Also must look for a getter name which uses property syntax.
1980    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1981    if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1982      ObjCInterfaceDecl *IFace = MD->getClassInterface();
1983      ObjCMethodDecl *Getter;
1984      // FIXME: need to also look locally in the implementation.
1985      if ((Getter = IFace->lookupClassMethod(Sel))) {
1986        // Check the use of this method.
1987        if (DiagnoseUseOfDecl(Getter, MemberLoc))
1988          return ExprError();
1989      }
1990      // If we found a getter then this may be a valid dot-reference, we
1991      // will look for the matching setter, in case it is needed.
1992      Selector SetterSel =
1993        SelectorTable::constructSetterName(PP.getIdentifierTable(),
1994                                           PP.getSelectorTable(), &Member);
1995      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1996      if (!Setter) {
1997        // If this reference is in an @implementation, also check for 'private'
1998        // methods.
1999        if (ObjCImplementationDecl *ImpDecl =
2000            ObjCImplementations[IFace->getIdentifier()])
2001          Setter = ImpDecl->getInstanceMethod(SetterSel);
2002      }
2003      // Look through local category implementations associated with the class.
2004      if (!Setter) {
2005        for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2006          if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2007            Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2008        }
2009      }
2010
2011      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2012        return ExprError();
2013
2014      if (Getter || Setter) {
2015        QualType PType;
2016
2017        if (Getter)
2018          PType = Getter->getResultType();
2019        else {
2020          for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2021               E = Setter->param_end(); PI != E; ++PI)
2022            PType = (*PI)->getType();
2023        }
2024        // FIXME: we must check that the setter has property type.
2025        return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2026                                        Setter, MemberLoc, BaseExpr));
2027      }
2028      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2029        << &Member << BaseType);
2030    }
2031  }
2032
2033  // Handle 'field access' to vectors, such as 'V.xx'.
2034  if (BaseType->isExtVectorType()) {
2035    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2036    if (ret.isNull())
2037      return ExprError();
2038    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
2039                                                    MemberLoc));
2040  }
2041
2042  return ExprError(Diag(MemberLoc,
2043                        diag::err_typecheck_member_reference_struct_union)
2044                     << BaseType << BaseExpr->getSourceRange());
2045}
2046
2047/// ConvertArgumentsForCall - Converts the arguments specified in
2048/// Args/NumArgs to the parameter types of the function FDecl with
2049/// function prototype Proto. Call is the call expression itself, and
2050/// Fn is the function expression. For a C++ member function, this
2051/// routine does not attempt to convert the object argument. Returns
2052/// true if the call is ill-formed.
2053bool
2054Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2055                              FunctionDecl *FDecl,
2056                              const FunctionProtoType *Proto,
2057                              Expr **Args, unsigned NumArgs,
2058                              SourceLocation RParenLoc) {
2059  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
2060  // assignment, to the types of the corresponding parameter, ...
2061  unsigned NumArgsInProto = Proto->getNumArgs();
2062  unsigned NumArgsToCheck = NumArgs;
2063  bool Invalid = false;
2064
2065  // If too few arguments are available (and we don't have default
2066  // arguments for the remaining parameters), don't make the call.
2067  if (NumArgs < NumArgsInProto) {
2068    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2069      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2070        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2071    // Use default arguments for missing arguments
2072    NumArgsToCheck = NumArgsInProto;
2073    Call->setNumArgs(Context, NumArgsInProto);
2074  }
2075
2076  // If too many are passed and not variadic, error on the extras and drop
2077  // them.
2078  if (NumArgs > NumArgsInProto) {
2079    if (!Proto->isVariadic()) {
2080      Diag(Args[NumArgsInProto]->getLocStart(),
2081           diag::err_typecheck_call_too_many_args)
2082        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2083        << SourceRange(Args[NumArgsInProto]->getLocStart(),
2084                       Args[NumArgs-1]->getLocEnd());
2085      // This deletes the extra arguments.
2086      Call->setNumArgs(Context, NumArgsInProto);
2087      Invalid = true;
2088    }
2089    NumArgsToCheck = NumArgsInProto;
2090  }
2091
2092  // Continue to check argument types (even if we have too few/many args).
2093  for (unsigned i = 0; i != NumArgsToCheck; i++) {
2094    QualType ProtoArgType = Proto->getArgType(i);
2095
2096    Expr *Arg;
2097    if (i < NumArgs) {
2098      Arg = Args[i];
2099
2100      // Pass the argument.
2101      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2102        return true;
2103    } else
2104      // We already type-checked the argument, so we know it works.
2105      Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
2106    QualType ArgType = Arg->getType();
2107
2108    Call->setArg(i, Arg);
2109  }
2110
2111  // If this is a variadic call, handle args passed through "...".
2112  if (Proto->isVariadic()) {
2113    VariadicCallType CallType = VariadicFunction;
2114    if (Fn->getType()->isBlockPointerType())
2115      CallType = VariadicBlock; // Block
2116    else if (isa<MemberExpr>(Fn))
2117      CallType = VariadicMethod;
2118
2119    // Promote the arguments (C99 6.5.2.2p7).
2120    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2121      Expr *Arg = Args[i];
2122      DefaultVariadicArgumentPromotion(Arg, CallType);
2123      Call->setArg(i, Arg);
2124    }
2125  }
2126
2127  return Invalid;
2128}
2129
2130/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2131/// This provides the location of the left/right parens and a list of comma
2132/// locations.
2133Action::OwningExprResult
2134Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2135                    MultiExprArg args,
2136                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2137  unsigned NumArgs = args.size();
2138  Expr *Fn = static_cast<Expr *>(fn.release());
2139  Expr **Args = reinterpret_cast<Expr**>(args.release());
2140  assert(Fn && "no function call expression");
2141  FunctionDecl *FDecl = NULL;
2142  DeclarationName UnqualifiedName;
2143
2144  if (getLangOptions().CPlusPlus) {
2145    // Determine whether this is a dependent call inside a C++ template,
2146    // in which case we won't do any semantic analysis now.
2147    // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2148    bool Dependent = false;
2149    if (Fn->isTypeDependent())
2150      Dependent = true;
2151    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2152      Dependent = true;
2153
2154    if (Dependent)
2155      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2156                                          Context.DependentTy, RParenLoc));
2157
2158    // Determine whether this is a call to an object (C++ [over.call.object]).
2159    if (Fn->getType()->isRecordType())
2160      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2161                                                CommaLocs, RParenLoc));
2162
2163    // Determine whether this is a call to a member function.
2164    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2165      if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2166          isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
2167        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2168                                               CommaLocs, RParenLoc));
2169  }
2170
2171  // If we're directly calling a function, get the appropriate declaration.
2172  DeclRefExpr *DRExpr = NULL;
2173  Expr *FnExpr = Fn;
2174  bool ADL = true;
2175  while (true) {
2176    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2177      FnExpr = IcExpr->getSubExpr();
2178    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2179      // Parentheses around a function disable ADL
2180      // (C++0x [basic.lookup.argdep]p1).
2181      ADL = false;
2182      FnExpr = PExpr->getSubExpr();
2183    } else if (isa<UnaryOperator>(FnExpr) &&
2184               cast<UnaryOperator>(FnExpr)->getOpcode()
2185                 == UnaryOperator::AddrOf) {
2186      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2187    } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2188      // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2189      ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2190      break;
2191    } else if (UnresolvedFunctionNameExpr *DepName
2192                 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2193      UnqualifiedName = DepName->getName();
2194      break;
2195    } else {
2196      // Any kind of name that does not refer to a declaration (or
2197      // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2198      ADL = false;
2199      break;
2200    }
2201  }
2202
2203  OverloadedFunctionDecl *Ovl = 0;
2204  if (DRExpr) {
2205    FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
2206    Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2207  }
2208
2209  if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2210    // We don't perform ADL for implicit declarations of builtins.
2211    if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
2212      ADL = false;
2213
2214    // We don't perform ADL in C.
2215    if (!getLangOptions().CPlusPlus)
2216      ADL = false;
2217
2218    if (Ovl || ADL) {
2219      FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2220                                      UnqualifiedName, LParenLoc, Args,
2221                                      NumArgs, CommaLocs, RParenLoc, ADL);
2222      if (!FDecl)
2223        return ExprError();
2224
2225      // Update Fn to refer to the actual function selected.
2226      Expr *NewFn = 0;
2227      if (QualifiedDeclRefExpr *QDRExpr
2228            = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
2229        NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2230                                                   QDRExpr->getLocation(),
2231                                                   false, false,
2232                                          QDRExpr->getSourceRange().getBegin());
2233      else
2234        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2235                                          Fn->getSourceRange().getBegin());
2236      Fn->Destroy(Context);
2237      Fn = NewFn;
2238    }
2239  }
2240
2241  // Promote the function operand.
2242  UsualUnaryConversions(Fn);
2243
2244  // Make the call expr early, before semantic checks.  This guarantees cleanup
2245  // of arguments and function on error.
2246  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2247                                                               Args, NumArgs,
2248                                                               Context.BoolTy,
2249                                                               RParenLoc));
2250
2251  const FunctionType *FuncT;
2252  if (!Fn->getType()->isBlockPointerType()) {
2253    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2254    // have type pointer to function".
2255    const PointerType *PT = Fn->getType()->getAsPointerType();
2256    if (PT == 0)
2257      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2258        << Fn->getType() << Fn->getSourceRange());
2259    FuncT = PT->getPointeeType()->getAsFunctionType();
2260  } else { // This is a block call.
2261    FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2262                getAsFunctionType();
2263  }
2264  if (FuncT == 0)
2265    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2266      << Fn->getType() << Fn->getSourceRange());
2267
2268  // We know the result type of the call, set it.
2269  TheCall->setType(FuncT->getResultType().getNonReferenceType());
2270
2271  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2272    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2273                                RParenLoc))
2274      return ExprError();
2275  } else {
2276    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
2277
2278    // Promote the arguments (C99 6.5.2.2p6).
2279    for (unsigned i = 0; i != NumArgs; i++) {
2280      Expr *Arg = Args[i];
2281      DefaultArgumentPromotion(Arg);
2282      TheCall->setArg(i, Arg);
2283    }
2284  }
2285
2286  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2287    if (!Method->isStatic())
2288      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2289        << Fn->getSourceRange());
2290
2291  // Do special checking on direct calls to functions.
2292  if (FDecl)
2293    return CheckFunctionCall(FDecl, TheCall.take());
2294
2295  return Owned(TheCall.take());
2296}
2297
2298Action::OwningExprResult
2299Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2300                           SourceLocation RParenLoc, ExprArg InitExpr) {
2301  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
2302  QualType literalType = QualType::getFromOpaquePtr(Ty);
2303  // FIXME: put back this assert when initializers are worked out.
2304  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
2305  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
2306
2307  if (literalType->isArrayType()) {
2308    if (literalType->isVariableArrayType())
2309      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2310        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
2311  } else if (RequireCompleteType(LParenLoc, literalType,
2312                                    diag::err_typecheck_decl_incomplete_type,
2313                SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
2314    return ExprError();
2315
2316  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
2317                            DeclarationName(), /*FIXME:DirectInit=*/false))
2318    return ExprError();
2319
2320  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
2321  if (isFileScope) { // 6.5.2.5p3
2322    if (CheckForConstantInitializer(literalExpr, literalType))
2323      return ExprError();
2324  }
2325  InitExpr.release();
2326  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2327                                                 literalExpr, isFileScope));
2328}
2329
2330Action::OwningExprResult
2331Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2332                    InitListDesignations &Designators,
2333                    SourceLocation RBraceLoc) {
2334  unsigned NumInit = initlist.size();
2335  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
2336
2337  // Semantic analysis for initializers is done by ActOnDeclarator() and
2338  // CheckInitializer() - it requires knowledge of the object being intialized.
2339
2340  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
2341                                               RBraceLoc);
2342  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
2343  return Owned(E);
2344}
2345
2346/// CheckCastTypes - Check type constraints for casting between types.
2347bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
2348  UsualUnaryConversions(castExpr);
2349
2350  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2351  // type needs to be scalar.
2352  if (castType->isVoidType()) {
2353    // Cast to void allows any expr type.
2354  } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2355    // We can't check any more until template instantiation time.
2356  } else if (!castType->isScalarType() && !castType->isVectorType()) {
2357    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2358        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2359        (castType->isStructureType() || castType->isUnionType())) {
2360      // GCC struct/union extension: allow cast to self.
2361      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2362        << castType << castExpr->getSourceRange();
2363    } else if (castType->isUnionType()) {
2364      // GCC cast to union extension
2365      RecordDecl *RD = castType->getAsRecordType()->getDecl();
2366      RecordDecl::field_iterator Field, FieldEnd;
2367      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2368           Field != FieldEnd; ++Field) {
2369        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2370            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2371          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2372            << castExpr->getSourceRange();
2373          break;
2374        }
2375      }
2376      if (Field == FieldEnd)
2377        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2378          << castExpr->getType() << castExpr->getSourceRange();
2379    } else {
2380      // Reject any other conversions to non-scalar types.
2381      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
2382        << castType << castExpr->getSourceRange();
2383    }
2384  } else if (!castExpr->getType()->isScalarType() &&
2385             !castExpr->getType()->isVectorType()) {
2386    return Diag(castExpr->getLocStart(),
2387                diag::err_typecheck_expect_scalar_operand)
2388      << castExpr->getType() << castExpr->getSourceRange();
2389  } else if (castExpr->getType()->isVectorType()) {
2390    if (CheckVectorCast(TyR, castExpr->getType(), castType))
2391      return true;
2392  } else if (castType->isVectorType()) {
2393    if (CheckVectorCast(TyR, castType, castExpr->getType()))
2394      return true;
2395  } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
2396    return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
2397  }
2398  return false;
2399}
2400
2401bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
2402  assert(VectorTy->isVectorType() && "Not a vector type!");
2403
2404  if (Ty->isVectorType() || Ty->isIntegerType()) {
2405    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
2406      return Diag(R.getBegin(),
2407                  Ty->isVectorType() ?
2408                  diag::err_invalid_conversion_between_vectors :
2409                  diag::err_invalid_conversion_between_vector_and_integer)
2410        << VectorTy << Ty << R;
2411  } else
2412    return Diag(R.getBegin(),
2413                diag::err_invalid_conversion_between_vector_and_scalar)
2414      << VectorTy << Ty << R;
2415
2416  return false;
2417}
2418
2419Action::OwningExprResult
2420Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2421                    SourceLocation RParenLoc, ExprArg Op) {
2422  assert((Ty != 0) && (Op.get() != 0) &&
2423         "ActOnCastExpr(): missing type or expr");
2424
2425  Expr *castExpr = static_cast<Expr*>(Op.release());
2426  QualType castType = QualType::getFromOpaquePtr(Ty);
2427
2428  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
2429    return ExprError();
2430  return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
2431                                            LParenLoc, RParenLoc));
2432}
2433
2434/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2435/// In that case, lhs = cond.
2436/// C99 6.5.15
2437QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2438                                        SourceLocation QuestionLoc) {
2439  UsualUnaryConversions(Cond);
2440  UsualUnaryConversions(LHS);
2441  UsualUnaryConversions(RHS);
2442  QualType CondTy = Cond->getType();
2443  QualType LHSTy = LHS->getType();
2444  QualType RHSTy = RHS->getType();
2445
2446  // first, check the condition.
2447  if (!Cond->isTypeDependent()) {
2448    if (!CondTy->isScalarType()) { // C99 6.5.15p2
2449      Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2450        << CondTy;
2451      return QualType();
2452    }
2453  }
2454
2455  // Now check the two expressions.
2456  if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
2457    return Context.DependentTy;
2458
2459  // If both operands have arithmetic type, do the usual arithmetic conversions
2460  // to find a common type: C99 6.5.15p3,5.
2461  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2462    UsualArithmeticConversions(LHS, RHS);
2463    return LHS->getType();
2464  }
2465
2466  // If both operands are the same structure or union type, the result is that
2467  // type.
2468  if (const RecordType *LHSRT = LHSTy->getAsRecordType()) {    // C99 6.5.15p3
2469    if (const RecordType *RHSRT = RHSTy->getAsRecordType())
2470      if (LHSRT->getDecl() == RHSRT->getDecl())
2471        // "If both the operands have structure or union type, the result has
2472        // that type."  This implies that CV qualifiers are dropped.
2473        return LHSTy.getUnqualifiedType();
2474  }
2475
2476  // C99 6.5.15p5: "If both operands have void type, the result has void type."
2477  // The following || allows only one side to be void (a GCC-ism).
2478  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2479    if (!LHSTy->isVoidType())
2480      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2481        << RHS->getSourceRange();
2482    if (!RHSTy->isVoidType())
2483      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2484        << LHS->getSourceRange();
2485    ImpCastExprToType(LHS, Context.VoidTy);
2486    ImpCastExprToType(RHS, Context.VoidTy);
2487    return Context.VoidTy;
2488  }
2489  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2490  // the type of the other operand."
2491  if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2492       Context.isObjCObjectPointerType(LHSTy)) &&
2493      RHS->isNullPointerConstant(Context)) {
2494    ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2495    return LHSTy;
2496  }
2497  if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2498       Context.isObjCObjectPointerType(RHSTy)) &&
2499      LHS->isNullPointerConstant(Context)) {
2500    ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2501    return RHSTy;
2502  }
2503
2504  // Handle the case where both operands are pointers before we handle null
2505  // pointer constants in case both operands are null pointer constants.
2506  if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2507    if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
2508      // get the "pointed to" types
2509      QualType lhptee = LHSPT->getPointeeType();
2510      QualType rhptee = RHSPT->getPointeeType();
2511
2512      // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2513      if (lhptee->isVoidType() &&
2514          rhptee->isIncompleteOrObjectType()) {
2515        // Figure out necessary qualifiers (C99 6.5.15p6)
2516        QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
2517        QualType destType = Context.getPointerType(destPointee);
2518        ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2519        ImpCastExprToType(RHS, destType); // promote to void*
2520        return destType;
2521      }
2522      if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
2523        QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
2524        QualType destType = Context.getPointerType(destPointee);
2525        ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2526        ImpCastExprToType(RHS, destType); // promote to void*
2527        return destType;
2528      }
2529
2530      if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2531        // Two identical pointer types are always compatible.
2532        return LHSTy;
2533      }
2534
2535      QualType compositeType = LHSTy;
2536
2537      // If either type is an Objective-C object type then check
2538      // compatibility according to Objective-C.
2539      if (Context.isObjCObjectPointerType(LHSTy) ||
2540          Context.isObjCObjectPointerType(RHSTy)) {
2541        // If both operands are interfaces and either operand can be
2542        // assigned to the other, use that type as the composite
2543        // type. This allows
2544        //   xxx ? (A*) a : (B*) b
2545        // where B is a subclass of A.
2546        //
2547        // Additionally, as for assignment, if either type is 'id'
2548        // allow silent coercion. Finally, if the types are
2549        // incompatible then make sure to use 'id' as the composite
2550        // type so the result is acceptable for sending messages to.
2551
2552        // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2553        // It could return the composite type.
2554        const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2555        const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2556        if (LHSIface && RHSIface &&
2557            Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2558          compositeType = LHSTy;
2559        } else if (LHSIface && RHSIface &&
2560                   Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
2561          compositeType = RHSTy;
2562        } else if (Context.isObjCIdStructType(lhptee) ||
2563                   Context.isObjCIdStructType(rhptee)) {
2564          compositeType = Context.getObjCIdType();
2565        } else {
2566          Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2567               << LHSTy << RHSTy
2568               << LHS->getSourceRange() << RHS->getSourceRange();
2569          QualType incompatTy = Context.getObjCIdType();
2570          ImpCastExprToType(LHS, incompatTy);
2571          ImpCastExprToType(RHS, incompatTy);
2572          return incompatTy;
2573        }
2574      } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2575                                             rhptee.getUnqualifiedType())) {
2576        Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2577          << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2578        // In this situation, we assume void* type. No especially good
2579        // reason, but this is what gcc does, and we do have to pick
2580        // to get a consistent AST.
2581        QualType incompatTy = Context.getPointerType(Context.VoidTy);
2582        ImpCastExprToType(LHS, incompatTy);
2583        ImpCastExprToType(RHS, incompatTy);
2584        return incompatTy;
2585      }
2586      // The pointer types are compatible.
2587      // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2588      // differently qualified versions of compatible types, the result type is
2589      // a pointer to an appropriately qualified version of the *composite*
2590      // type.
2591      // FIXME: Need to calculate the composite type.
2592      // FIXME: Need to add qualifiers
2593      ImpCastExprToType(LHS, compositeType);
2594      ImpCastExprToType(RHS, compositeType);
2595      return compositeType;
2596    }
2597  }
2598
2599  // Selection between block pointer types is ok as long as they are the same.
2600  if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2601      Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2602    return LHSTy;
2603
2604  // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2605  // evaluates to "struct objc_object *" (and is handled above when comparing
2606  // id with statically typed objects).
2607  if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
2608    // GCC allows qualified id and any Objective-C type to devolve to
2609    // id. Currently localizing to here until clear this should be
2610    // part of ObjCQualifiedIdTypesAreCompatible.
2611    if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
2612        (LHSTy->isObjCQualifiedIdType() &&
2613         Context.isObjCObjectPointerType(RHSTy)) ||
2614        (RHSTy->isObjCQualifiedIdType() &&
2615         Context.isObjCObjectPointerType(LHSTy))) {
2616      // FIXME: This is not the correct composite type. This only
2617      // happens to work because id can more or less be used anywhere,
2618      // however this may change the type of method sends.
2619      // FIXME: gcc adds some type-checking of the arguments and emits
2620      // (confusing) incompatible comparison warnings in some
2621      // cases. Investigate.
2622      QualType compositeType = Context.getObjCIdType();
2623      ImpCastExprToType(LHS, compositeType);
2624      ImpCastExprToType(RHS, compositeType);
2625      return compositeType;
2626    }
2627  }
2628
2629  // Otherwise, the operands are not compatible.
2630  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2631    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2632  return QualType();
2633}
2634
2635/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2636/// in the case of a the GNU conditional expr extension.
2637Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2638                                                  SourceLocation ColonLoc,
2639                                                  ExprArg Cond, ExprArg LHS,
2640                                                  ExprArg RHS) {
2641  Expr *CondExpr = (Expr *) Cond.get();
2642  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
2643
2644  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2645  // was the condition.
2646  bool isLHSNull = LHSExpr == 0;
2647  if (isLHSNull)
2648    LHSExpr = CondExpr;
2649
2650  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2651                                             RHSExpr, QuestionLoc);
2652  if (result.isNull())
2653    return ExprError();
2654
2655  Cond.release();
2656  LHS.release();
2657  RHS.release();
2658  return Owned(new (Context) ConditionalOperator(CondExpr,
2659                                                 isLHSNull ? 0 : LHSExpr,
2660                                                 RHSExpr, result));
2661}
2662
2663
2664// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2665// being closely modeled after the C99 spec:-). The odd characteristic of this
2666// routine is it effectively iqnores the qualifiers on the top level pointee.
2667// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2668// FIXME: add a couple examples in this comment.
2669Sema::AssignConvertType
2670Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2671  QualType lhptee, rhptee;
2672
2673  // get the "pointed to" type (ignoring qualifiers at the top level)
2674  lhptee = lhsType->getAsPointerType()->getPointeeType();
2675  rhptee = rhsType->getAsPointerType()->getPointeeType();
2676
2677  // make sure we operate on the canonical type
2678  lhptee = Context.getCanonicalType(lhptee);
2679  rhptee = Context.getCanonicalType(rhptee);
2680
2681  AssignConvertType ConvTy = Compatible;
2682
2683  // C99 6.5.16.1p1: This following citation is common to constraints
2684  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2685  // qualifiers of the type *pointed to* by the right;
2686  // FIXME: Handle ExtQualType
2687  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
2688    ConvTy = CompatiblePointerDiscardsQualifiers;
2689
2690  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2691  // incomplete type and the other is a pointer to a qualified or unqualified
2692  // version of void...
2693  if (lhptee->isVoidType()) {
2694    if (rhptee->isIncompleteOrObjectType())
2695      return ConvTy;
2696
2697    // As an extension, we allow cast to/from void* to function pointer.
2698    assert(rhptee->isFunctionType());
2699    return FunctionVoidPointer;
2700  }
2701
2702  if (rhptee->isVoidType()) {
2703    if (lhptee->isIncompleteOrObjectType())
2704      return ConvTy;
2705
2706    // As an extension, we allow cast to/from void* to function pointer.
2707    assert(lhptee->isFunctionType());
2708    return FunctionVoidPointer;
2709  }
2710  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2711  // unqualified versions of compatible types, ...
2712  if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2713                                  rhptee.getUnqualifiedType()))
2714    return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
2715  return ConvTy;
2716}
2717
2718/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2719/// block pointer types are compatible or whether a block and normal pointer
2720/// are compatible. It is more restrict than comparing two function pointer
2721// types.
2722Sema::AssignConvertType
2723Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2724                                          QualType rhsType) {
2725  QualType lhptee, rhptee;
2726
2727  // get the "pointed to" type (ignoring qualifiers at the top level)
2728  lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2729  rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2730
2731  // make sure we operate on the canonical type
2732  lhptee = Context.getCanonicalType(lhptee);
2733  rhptee = Context.getCanonicalType(rhptee);
2734
2735  AssignConvertType ConvTy = Compatible;
2736
2737  // For blocks we enforce that qualifiers are identical.
2738  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2739    ConvTy = CompatiblePointerDiscardsQualifiers;
2740
2741  if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2742    return IncompatibleBlockPointer;
2743  return ConvTy;
2744}
2745
2746/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2747/// has code to accommodate several GCC extensions when type checking
2748/// pointers. Here are some objectionable examples that GCC considers warnings:
2749///
2750///  int a, *pint;
2751///  short *pshort;
2752///  struct foo *pfoo;
2753///
2754///  pint = pshort; // warning: assignment from incompatible pointer type
2755///  a = pint; // warning: assignment makes integer from pointer without a cast
2756///  pint = a; // warning: assignment makes pointer from integer without a cast
2757///  pint = pfoo; // warning: assignment from incompatible pointer type
2758///
2759/// As a result, the code for dealing with pointers is more complex than the
2760/// C99 spec dictates.
2761///
2762Sema::AssignConvertType
2763Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
2764  // Get canonical types.  We're not formatting these types, just comparing
2765  // them.
2766  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2767  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
2768
2769  if (lhsType == rhsType)
2770    return Compatible; // Common case: fast path an exact match.
2771
2772  // If the left-hand side is a reference type, then we are in a
2773  // (rare!) case where we've allowed the use of references in C,
2774  // e.g., as a parameter type in a built-in function. In this case,
2775  // just make sure that the type referenced is compatible with the
2776  // right-hand side type. The caller is responsible for adjusting
2777  // lhsType so that the resulting expression does not have reference
2778  // type.
2779  if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2780    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
2781      return Compatible;
2782    return Incompatible;
2783  }
2784
2785  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2786    if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
2787      return Compatible;
2788    // Relax integer conversions like we do for pointers below.
2789    if (rhsType->isIntegerType())
2790      return IntToPointer;
2791    if (lhsType->isIntegerType())
2792      return PointerToInt;
2793    return IncompatibleObjCQualifiedId;
2794  }
2795
2796  if (lhsType->isVectorType() || rhsType->isVectorType()) {
2797    // For ExtVector, allow vector splats; float -> <n x float>
2798    if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2799      if (LV->getElementType() == rhsType)
2800        return Compatible;
2801
2802    // If we are allowing lax vector conversions, and LHS and RHS are both
2803    // vectors, the total size only needs to be the same. This is a bitcast;
2804    // no bits are changed but the result type is different.
2805    if (getLangOptions().LaxVectorConversions &&
2806        lhsType->isVectorType() && rhsType->isVectorType()) {
2807      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2808        return IncompatibleVectors;
2809    }
2810    return Incompatible;
2811  }
2812
2813  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
2814    return Compatible;
2815
2816  if (isa<PointerType>(lhsType)) {
2817    if (rhsType->isIntegerType())
2818      return IntToPointer;
2819
2820    if (isa<PointerType>(rhsType))
2821      return CheckPointerTypesForAssignment(lhsType, rhsType);
2822
2823    if (rhsType->getAsBlockPointerType()) {
2824      if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
2825        return Compatible;
2826
2827      // Treat block pointers as objects.
2828      if (getLangOptions().ObjC1 &&
2829          lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2830        return Compatible;
2831    }
2832    return Incompatible;
2833  }
2834
2835  if (isa<BlockPointerType>(lhsType)) {
2836    if (rhsType->isIntegerType())
2837      return IntToBlockPointer;
2838
2839    // Treat block pointers as objects.
2840    if (getLangOptions().ObjC1 &&
2841        rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2842      return Compatible;
2843
2844    if (rhsType->isBlockPointerType())
2845      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2846
2847    if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2848      if (RHSPT->getPointeeType()->isVoidType())
2849        return Compatible;
2850    }
2851    return Incompatible;
2852  }
2853
2854  if (isa<PointerType>(rhsType)) {
2855    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
2856    if (lhsType == Context.BoolTy)
2857      return Compatible;
2858
2859    if (lhsType->isIntegerType())
2860      return PointerToInt;
2861
2862    if (isa<PointerType>(lhsType))
2863      return CheckPointerTypesForAssignment(lhsType, rhsType);
2864
2865    if (isa<BlockPointerType>(lhsType) &&
2866        rhsType->getAsPointerType()->getPointeeType()->isVoidType())
2867      return Compatible;
2868    return Incompatible;
2869  }
2870
2871  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
2872    if (Context.typesAreCompatible(lhsType, rhsType))
2873      return Compatible;
2874  }
2875  return Incompatible;
2876}
2877
2878Sema::AssignConvertType
2879Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
2880  if (getLangOptions().CPlusPlus) {
2881    if (!lhsType->isRecordType()) {
2882      // C++ 5.17p3: If the left operand is not of class type, the
2883      // expression is implicitly converted (C++ 4) to the
2884      // cv-unqualified type of the left operand.
2885      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2886                                    "assigning"))
2887        return Incompatible;
2888      else
2889        return Compatible;
2890    }
2891
2892    // FIXME: Currently, we fall through and treat C++ classes like C
2893    // structures.
2894  }
2895
2896  // C99 6.5.16.1p1: the left operand is a pointer and the right is
2897  // a null pointer constant.
2898  if ((lhsType->isPointerType() ||
2899       lhsType->isObjCQualifiedIdType() ||
2900       lhsType->isBlockPointerType())
2901      && rExpr->isNullPointerConstant(Context)) {
2902    ImpCastExprToType(rExpr, lhsType);
2903    return Compatible;
2904  }
2905
2906  // This check seems unnatural, however it is necessary to ensure the proper
2907  // conversion of functions/arrays. If the conversion were done for all
2908  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
2909  // expressions that surpress this implicit conversion (&, sizeof).
2910  //
2911  // Suppress this for references: C++ 8.5.3p5.
2912  if (!lhsType->isReferenceType())
2913    DefaultFunctionArrayConversion(rExpr);
2914
2915  Sema::AssignConvertType result =
2916    CheckAssignmentConstraints(lhsType, rExpr->getType());
2917
2918  // C99 6.5.16.1p2: The value of the right operand is converted to the
2919  // type of the assignment expression.
2920  // CheckAssignmentConstraints allows the left-hand side to be a reference,
2921  // so that we can use references in built-in functions even in C.
2922  // The getNonReferenceType() call makes sure that the resulting expression
2923  // does not have reference type.
2924  if (rExpr->getType() != lhsType)
2925    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
2926  return result;
2927}
2928
2929Sema::AssignConvertType
2930Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2931  return CheckAssignmentConstraints(lhsType, rhsType);
2932}
2933
2934QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
2935  Diag(Loc, diag::err_typecheck_invalid_operands)
2936    << lex->getType() << rex->getType()
2937    << lex->getSourceRange() << rex->getSourceRange();
2938  return QualType();
2939}
2940
2941inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
2942                                                              Expr *&rex) {
2943  // For conversion purposes, we ignore any qualifiers.
2944  // For example, "const float" and "float" are equivalent.
2945  QualType lhsType =
2946    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2947  QualType rhsType =
2948    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
2949
2950  // If the vector types are identical, return.
2951  if (lhsType == rhsType)
2952    return lhsType;
2953
2954  // Handle the case of a vector & extvector type of the same size and element
2955  // type.  It would be nice if we only had one vector type someday.
2956  if (getLangOptions().LaxVectorConversions) {
2957    // FIXME: Should we warn here?
2958    if (const VectorType *LV = lhsType->getAsVectorType()) {
2959      if (const VectorType *RV = rhsType->getAsVectorType())
2960        if (LV->getElementType() == RV->getElementType() &&
2961            LV->getNumElements() == RV->getNumElements()) {
2962          return lhsType->isExtVectorType() ? lhsType : rhsType;
2963        }
2964    }
2965  }
2966
2967  // If the lhs is an extended vector and the rhs is a scalar of the same type
2968  // or a literal, promote the rhs to the vector type.
2969  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
2970    QualType eltType = V->getElementType();
2971
2972    if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2973        (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2974        (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
2975      ImpCastExprToType(rex, lhsType);
2976      return lhsType;
2977    }
2978  }
2979
2980  // If the rhs is an extended vector and the lhs is a scalar of the same type,
2981  // promote the lhs to the vector type.
2982  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
2983    QualType eltType = V->getElementType();
2984
2985    if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2986        (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2987        (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
2988      ImpCastExprToType(lex, rhsType);
2989      return rhsType;
2990    }
2991  }
2992
2993  // You cannot convert between vector values of different size.
2994  Diag(Loc, diag::err_typecheck_vector_not_convertable)
2995    << lex->getType() << rex->getType()
2996    << lex->getSourceRange() << rex->getSourceRange();
2997  return QualType();
2998}
2999
3000inline QualType Sema::CheckMultiplyDivideOperands(
3001  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3002{
3003  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3004    return CheckVectorOperands(Loc, lex, rex);
3005
3006  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3007
3008  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3009    return compType;
3010  return InvalidOperands(Loc, lex, rex);
3011}
3012
3013inline QualType Sema::CheckRemainderOperands(
3014  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3015{
3016  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3017    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3018      return CheckVectorOperands(Loc, lex, rex);
3019    return InvalidOperands(Loc, lex, rex);
3020  }
3021
3022  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3023
3024  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3025    return compType;
3026  return InvalidOperands(Loc, lex, rex);
3027}
3028
3029inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
3030  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3031{
3032  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3033    return CheckVectorOperands(Loc, lex, rex);
3034
3035  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3036
3037  // handle the common case first (both operands are arithmetic).
3038  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3039    return compType;
3040
3041  // Put any potential pointer into PExp
3042  Expr* PExp = lex, *IExp = rex;
3043  if (IExp->getType()->isPointerType())
3044    std::swap(PExp, IExp);
3045
3046  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3047    if (IExp->getType()->isIntegerType()) {
3048      // Check for arithmetic on pointers to incomplete types
3049      if (!PTy->getPointeeType()->isObjectType()) {
3050        if (PTy->getPointeeType()->isVoidType()) {
3051          if (getLangOptions().CPlusPlus) {
3052            Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3053              << lex->getSourceRange() << rex->getSourceRange();
3054            return QualType();
3055          }
3056
3057          // GNU extension: arithmetic on pointer to void
3058          Diag(Loc, diag::ext_gnu_void_ptr)
3059            << lex->getSourceRange() << rex->getSourceRange();
3060        } else if (PTy->getPointeeType()->isFunctionType()) {
3061          if (getLangOptions().CPlusPlus) {
3062            Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3063              << lex->getType() << lex->getSourceRange();
3064            return QualType();
3065          }
3066
3067          // GNU extension: arithmetic on pointer to function
3068          Diag(Loc, diag::ext_gnu_ptr_func_arith)
3069            << lex->getType() << lex->getSourceRange();
3070        } else {
3071          RequireCompleteType(Loc, PTy->getPointeeType(),
3072                                 diag::err_typecheck_arithmetic_incomplete_type,
3073                                 lex->getSourceRange(), SourceRange(),
3074                                 lex->getType());
3075          return QualType();
3076        }
3077      }
3078      return PExp->getType();
3079    }
3080  }
3081
3082  return InvalidOperands(Loc, lex, rex);
3083}
3084
3085// C99 6.5.6
3086QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
3087                                        SourceLocation Loc, bool isCompAssign) {
3088  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3089    return CheckVectorOperands(Loc, lex, rex);
3090
3091  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3092
3093  // Enforce type constraints: C99 6.5.6p3.
3094
3095  // Handle the common case first (both operands are arithmetic).
3096  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3097    return compType;
3098
3099  // Either ptr - int   or   ptr - ptr.
3100  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
3101    QualType lpointee = LHSPTy->getPointeeType();
3102
3103    // The LHS must be an object type, not incomplete, function, etc.
3104    if (!lpointee->isObjectType()) {
3105      // Handle the GNU void* extension.
3106      if (lpointee->isVoidType()) {
3107        Diag(Loc, diag::ext_gnu_void_ptr)
3108          << lex->getSourceRange() << rex->getSourceRange();
3109      } else if (lpointee->isFunctionType()) {
3110        if (getLangOptions().CPlusPlus) {
3111          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3112            << lex->getType() << lex->getSourceRange();
3113          return QualType();
3114        }
3115
3116        // GNU extension: arithmetic on pointer to function
3117        Diag(Loc, diag::ext_gnu_ptr_func_arith)
3118          << lex->getType() << lex->getSourceRange();
3119      } else {
3120        Diag(Loc, diag::err_typecheck_sub_ptr_object)
3121          << lex->getType() << lex->getSourceRange();
3122        return QualType();
3123      }
3124    }
3125
3126    // The result type of a pointer-int computation is the pointer type.
3127    if (rex->getType()->isIntegerType())
3128      return lex->getType();
3129
3130    // Handle pointer-pointer subtractions.
3131    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
3132      QualType rpointee = RHSPTy->getPointeeType();
3133
3134      // RHS must be an object type, unless void (GNU).
3135      if (!rpointee->isObjectType()) {
3136        // Handle the GNU void* extension.
3137        if (rpointee->isVoidType()) {
3138          if (!lpointee->isVoidType())
3139            Diag(Loc, diag::ext_gnu_void_ptr)
3140              << lex->getSourceRange() << rex->getSourceRange();
3141        } else if (rpointee->isFunctionType()) {
3142          if (getLangOptions().CPlusPlus) {
3143            Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3144              << rex->getType() << rex->getSourceRange();
3145            return QualType();
3146          }
3147
3148          // GNU extension: arithmetic on pointer to function
3149          if (!lpointee->isFunctionType())
3150            Diag(Loc, diag::ext_gnu_ptr_func_arith)
3151              << lex->getType() << lex->getSourceRange();
3152        } else {
3153          Diag(Loc, diag::err_typecheck_sub_ptr_object)
3154            << rex->getType() << rex->getSourceRange();
3155          return QualType();
3156        }
3157      }
3158
3159      // Pointee types must be compatible.
3160      if (!Context.typesAreCompatible(
3161              Context.getCanonicalType(lpointee).getUnqualifiedType(),
3162              Context.getCanonicalType(rpointee).getUnqualifiedType())) {
3163        Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
3164          << lex->getType() << rex->getType()
3165          << lex->getSourceRange() << rex->getSourceRange();
3166        return QualType();
3167      }
3168
3169      return Context.getPointerDiffType();
3170    }
3171  }
3172
3173  return InvalidOperands(Loc, lex, rex);
3174}
3175
3176// C99 6.5.7
3177QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
3178                                  bool isCompAssign) {
3179  // C99 6.5.7p2: Each of the operands shall have integer type.
3180  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
3181    return InvalidOperands(Loc, lex, rex);
3182
3183  // Shifts don't perform usual arithmetic conversions, they just do integer
3184  // promotions on each operand. C99 6.5.7p3
3185  if (!isCompAssign)
3186    UsualUnaryConversions(lex);
3187  UsualUnaryConversions(rex);
3188
3189  // "The type of the result is that of the promoted left operand."
3190  return lex->getType();
3191}
3192
3193// C99 6.5.8
3194QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
3195                                    bool isRelational) {
3196  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3197    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
3198
3199  // C99 6.5.8p3 / C99 6.5.9p4
3200  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3201    UsualArithmeticConversions(lex, rex);
3202  else {
3203    UsualUnaryConversions(lex);
3204    UsualUnaryConversions(rex);
3205  }
3206  QualType lType = lex->getType();
3207  QualType rType = rex->getType();
3208
3209  if (!lType->isFloatingType()) {
3210    // For non-floating point types, check for self-comparisons of the form
3211    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
3212    // often indicate logic errors in the program.
3213    Expr *LHSStripped = lex->IgnoreParens();
3214    Expr *RHSStripped = rex->IgnoreParens();
3215    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3216      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
3217        if (DRL->getDecl() == DRR->getDecl())
3218          Diag(Loc, diag::warn_selfcomparison);
3219
3220    if (isa<CastExpr>(LHSStripped))
3221      LHSStripped = LHSStripped->IgnoreParenCasts();
3222    if (isa<CastExpr>(RHSStripped))
3223      RHSStripped = RHSStripped->IgnoreParenCasts();
3224
3225    // Warn about comparisons against a string constant (unless the other
3226    // operand is null), the user probably wants strcmp.
3227    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
3228        !RHSStripped->isNullPointerConstant(Context))
3229      Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange();
3230    else if ((isa<StringLiteral>(RHSStripped) ||
3231              isa<ObjCEncodeExpr>(RHSStripped)) &&
3232             !LHSStripped->isNullPointerConstant(Context))
3233      Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange();
3234  }
3235
3236  // The result of comparisons is 'bool' in C++, 'int' in C.
3237  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
3238
3239  if (isRelational) {
3240    if (lType->isRealType() && rType->isRealType())
3241      return ResultTy;
3242  } else {
3243    // Check for comparisons of floating point operands using != and ==.
3244    if (lType->isFloatingType()) {
3245      assert(rType->isFloatingType());
3246      CheckFloatComparison(Loc,lex,rex);
3247    }
3248
3249    if (lType->isArithmeticType() && rType->isArithmeticType())
3250      return ResultTy;
3251  }
3252
3253  bool LHSIsNull = lex->isNullPointerConstant(Context);
3254  bool RHSIsNull = rex->isNullPointerConstant(Context);
3255
3256  // All of the following pointer related warnings are GCC extensions, except
3257  // when handling null pointer constants. One day, we can consider making them
3258  // errors (when -pedantic-errors is enabled).
3259  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
3260    QualType LCanPointeeTy =
3261      Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
3262    QualType RCanPointeeTy =
3263      Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
3264
3265    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
3266        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3267        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
3268                                    RCanPointeeTy.getUnqualifiedType()) &&
3269        !Context.areComparableObjCPointerTypes(lType, rType)) {
3270      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
3271        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3272    }
3273    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3274    return ResultTy;
3275  }
3276  // Handle block pointer types.
3277  if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3278    QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3279    QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3280
3281    if (!LHSIsNull && !RHSIsNull &&
3282        !Context.typesAreBlockCompatible(lpointee, rpointee)) {
3283      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3284        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3285    }
3286    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3287    return ResultTy;
3288  }
3289  // Allow block pointers to be compared with null pointer constants.
3290  if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3291      (lType->isPointerType() && rType->isBlockPointerType())) {
3292    if (!LHSIsNull && !RHSIsNull) {
3293      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3294        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3295    }
3296    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3297    return ResultTy;
3298  }
3299
3300  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
3301    if (lType->isPointerType() || rType->isPointerType()) {
3302      const PointerType *LPT = lType->getAsPointerType();
3303      const PointerType *RPT = rType->getAsPointerType();
3304      bool LPtrToVoid = LPT ?
3305        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3306      bool RPtrToVoid = RPT ?
3307        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3308
3309      if (!LPtrToVoid && !RPtrToVoid &&
3310          !Context.typesAreCompatible(lType, rType)) {
3311        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
3312          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3313        ImpCastExprToType(rex, lType);
3314        return ResultTy;
3315      }
3316      ImpCastExprToType(rex, lType);
3317      return ResultTy;
3318    }
3319    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3320      ImpCastExprToType(rex, lType);
3321      return ResultTy;
3322    } else {
3323      if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
3324        Diag(Loc, diag::warn_incompatible_qualified_id_operands)
3325          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3326        ImpCastExprToType(rex, lType);
3327        return ResultTy;
3328      }
3329    }
3330  }
3331  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3332       rType->isIntegerType()) {
3333    if (!RHSIsNull)
3334      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3335        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3336    ImpCastExprToType(rex, lType); // promote the integer to pointer
3337    return ResultTy;
3338  }
3339  if (lType->isIntegerType() &&
3340      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
3341    if (!LHSIsNull)
3342      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3343        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3344    ImpCastExprToType(lex, rType); // promote the integer to pointer
3345    return ResultTy;
3346  }
3347  // Handle block pointers.
3348  if (lType->isBlockPointerType() && rType->isIntegerType()) {
3349    if (!RHSIsNull)
3350      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3351        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3352    ImpCastExprToType(rex, lType); // promote the integer to pointer
3353    return ResultTy;
3354  }
3355  if (lType->isIntegerType() && rType->isBlockPointerType()) {
3356    if (!LHSIsNull)
3357      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3358        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3359    ImpCastExprToType(lex, rType); // promote the integer to pointer
3360    return ResultTy;
3361  }
3362  return InvalidOperands(Loc, lex, rex);
3363}
3364
3365/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3366/// operates on extended vector types.  Instead of producing an IntTy result,
3367/// like a scalar comparison, a vector comparison produces a vector of integer
3368/// types.
3369QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
3370                                          SourceLocation Loc,
3371                                          bool isRelational) {
3372  // Check to make sure we're operating on vectors of the same type and width,
3373  // Allowing one side to be a scalar of element type.
3374  QualType vType = CheckVectorOperands(Loc, lex, rex);
3375  if (vType.isNull())
3376    return vType;
3377
3378  QualType lType = lex->getType();
3379  QualType rType = rex->getType();
3380
3381  // For non-floating point types, check for self-comparisons of the form
3382  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
3383  // often indicate logic errors in the program.
3384  if (!lType->isFloatingType()) {
3385    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3386      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3387        if (DRL->getDecl() == DRR->getDecl())
3388          Diag(Loc, diag::warn_selfcomparison);
3389  }
3390
3391  // Check for comparisons of floating point operands using != and ==.
3392  if (!isRelational && lType->isFloatingType()) {
3393    assert (rType->isFloatingType());
3394    CheckFloatComparison(Loc,lex,rex);
3395  }
3396
3397  // Return the type for the comparison, which is the same as vector type for
3398  // integer vectors, or an integer type of identical size and number of
3399  // elements for floating point vectors.
3400  if (lType->isIntegerType())
3401    return lType;
3402
3403  const VectorType *VTy = lType->getAsVectorType();
3404  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
3405  if (TypeSize == Context.getTypeSize(Context.IntTy))
3406    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
3407  else if (TypeSize == Context.getTypeSize(Context.LongTy))
3408    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3409
3410  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3411         "Unhandled vector element size in vector compare");
3412  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3413}
3414
3415inline QualType Sema::CheckBitwiseOperands(
3416  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3417{
3418  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3419    return CheckVectorOperands(Loc, lex, rex);
3420
3421  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3422
3423  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3424    return compType;
3425  return InvalidOperands(Loc, lex, rex);
3426}
3427
3428inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
3429  Expr *&lex, Expr *&rex, SourceLocation Loc)
3430{
3431  UsualUnaryConversions(lex);
3432  UsualUnaryConversions(rex);
3433
3434  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
3435    return Context.IntTy;
3436  return InvalidOperands(Loc, lex, rex);
3437}
3438
3439/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3440/// is a read-only property; return true if so. A readonly property expression
3441/// depends on various declarations and thus must be treated specially.
3442///
3443static bool IsReadonlyProperty(Expr *E, Sema &S)
3444{
3445  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3446    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3447    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3448      QualType BaseType = PropExpr->getBase()->getType();
3449      if (const PointerType *PTy = BaseType->getAsPointerType())
3450        if (const ObjCInterfaceType *IFTy =
3451            PTy->getPointeeType()->getAsObjCInterfaceType())
3452          if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3453            if (S.isPropertyReadonly(PDecl, IFace))
3454              return true;
3455    }
3456  }
3457  return false;
3458}
3459
3460/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
3461/// emit an error and return true.  If so, return false.
3462static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
3463  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3464  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3465    IsLV = Expr::MLV_ReadonlyProperty;
3466  if (IsLV == Expr::MLV_Valid)
3467    return false;
3468
3469  unsigned Diag = 0;
3470  bool NeedType = false;
3471  switch (IsLV) { // C99 6.5.16p2
3472  default: assert(0 && "Unknown result from isModifiableLvalue!");
3473  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
3474  case Expr::MLV_ArrayType:
3475    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3476    NeedType = true;
3477    break;
3478  case Expr::MLV_NotObjectType:
3479    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3480    NeedType = true;
3481    break;
3482  case Expr::MLV_LValueCast:
3483    Diag = diag::err_typecheck_lvalue_casts_not_supported;
3484    break;
3485  case Expr::MLV_InvalidExpression:
3486    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3487    break;
3488  case Expr::MLV_IncompleteType:
3489  case Expr::MLV_IncompleteVoidType:
3490    return S.RequireCompleteType(Loc, E->getType(),
3491                      diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3492                                    E->getSourceRange());
3493  case Expr::MLV_DuplicateVectorComponents:
3494    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3495    break;
3496  case Expr::MLV_NotBlockQualified:
3497    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3498    break;
3499  case Expr::MLV_ReadonlyProperty:
3500    Diag = diag::error_readonly_property_assignment;
3501    break;
3502  case Expr::MLV_NoSetterProperty:
3503    Diag = diag::error_nosetter_property_assignment;
3504    break;
3505  }
3506
3507  if (NeedType)
3508    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
3509  else
3510    S.Diag(Loc, Diag) << E->getSourceRange();
3511  return true;
3512}
3513
3514
3515
3516// C99 6.5.16.1
3517QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3518                                       SourceLocation Loc,
3519                                       QualType CompoundType) {
3520  // Verify that LHS is a modifiable lvalue, and emit error if not.
3521  if (CheckForModifiableLvalue(LHS, Loc, *this))
3522    return QualType();
3523
3524  QualType LHSType = LHS->getType();
3525  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
3526
3527  AssignConvertType ConvTy;
3528  if (CompoundType.isNull()) {
3529    // Simple assignment "x = y".
3530    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
3531    // Special case of NSObject attributes on c-style pointer types.
3532    if (ConvTy == IncompatiblePointer &&
3533        ((Context.isObjCNSObjectType(LHSType) &&
3534          Context.isObjCObjectPointerType(RHSType)) ||
3535         (Context.isObjCNSObjectType(RHSType) &&
3536          Context.isObjCObjectPointerType(LHSType))))
3537      ConvTy = Compatible;
3538
3539    // If the RHS is a unary plus or minus, check to see if they = and + are
3540    // right next to each other.  If so, the user may have typo'd "x =+ 4"
3541    // instead of "x += 4".
3542    Expr *RHSCheck = RHS;
3543    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3544      RHSCheck = ICE->getSubExpr();
3545    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3546      if ((UO->getOpcode() == UnaryOperator::Plus ||
3547           UO->getOpcode() == UnaryOperator::Minus) &&
3548          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
3549          // Only if the two operators are exactly adjacent.
3550          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3551          // And there is a space or other character before the subexpr of the
3552          // unary +/-.  We don't want to warn on "x=-1".
3553          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3554          UO->getSubExpr()->getLocStart().isFileID()) {
3555        Diag(Loc, diag::warn_not_compound_assign)
3556          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3557          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
3558      }
3559    }
3560  } else {
3561    // Compound assignment "x += y"
3562    ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
3563  }
3564
3565  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3566                               RHS, "assigning"))
3567    return QualType();
3568
3569  // C99 6.5.16p3: The type of an assignment expression is the type of the
3570  // left operand unless the left operand has qualified type, in which case
3571  // it is the unqualified version of the type of the left operand.
3572  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3573  // is converted to the type of the assignment expression (above).
3574  // C++ 5.17p1: the type of the assignment expression is that of its left
3575  // oprdu.
3576  return LHSType.getUnqualifiedType();
3577}
3578
3579// C99 6.5.17
3580QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3581  // FIXME: what is required for LHS?
3582
3583  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
3584  DefaultFunctionArrayConversion(RHS);
3585  return RHS->getType();
3586}
3587
3588/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3589/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
3590QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3591                                              bool isInc) {
3592  if (Op->isTypeDependent())
3593    return Context.DependentTy;
3594
3595  QualType ResType = Op->getType();
3596  assert(!ResType.isNull() && "no type for increment/decrement expression");
3597
3598  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3599    // Decrement of bool is not allowed.
3600    if (!isInc) {
3601      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3602      return QualType();
3603    }
3604    // Increment of bool sets it to true, but is deprecated.
3605    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3606  } else if (ResType->isRealType()) {
3607    // OK!
3608  } else if (const PointerType *PT = ResType->getAsPointerType()) {
3609    // C99 6.5.2.4p2, 6.5.6p2
3610    if (PT->getPointeeType()->isObjectType()) {
3611      // Pointer to object is ok!
3612    } else if (PT->getPointeeType()->isVoidType()) {
3613      if (getLangOptions().CPlusPlus) {
3614        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3615          << Op->getSourceRange();
3616        return QualType();
3617      }
3618
3619      // Pointer to void is a GNU extension in C.
3620      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3621    } else if (PT->getPointeeType()->isFunctionType()) {
3622      if (getLangOptions().CPlusPlus) {
3623        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3624          << Op->getType() << Op->getSourceRange();
3625        return QualType();
3626      }
3627
3628      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
3629        << ResType << Op->getSourceRange();
3630    } else {
3631      RequireCompleteType(OpLoc, PT->getPointeeType(),
3632                             diag::err_typecheck_arithmetic_incomplete_type,
3633                             Op->getSourceRange(), SourceRange(),
3634                             ResType);
3635      return QualType();
3636    }
3637  } else if (ResType->isComplexType()) {
3638    // C99 does not support ++/-- on complex types, we allow as an extension.
3639    Diag(OpLoc, diag::ext_integer_increment_complex)
3640      << ResType << Op->getSourceRange();
3641  } else {
3642    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
3643      << ResType << Op->getSourceRange();
3644    return QualType();
3645  }
3646  // At this point, we know we have a real, complex or pointer type.
3647  // Now make sure the operand is a modifiable lvalue.
3648  if (CheckForModifiableLvalue(Op, OpLoc, *this))
3649    return QualType();
3650  return ResType;
3651}
3652
3653/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
3654/// This routine allows us to typecheck complex/recursive expressions
3655/// where the declaration is needed for type checking. We only need to
3656/// handle cases when the expression references a function designator
3657/// or is an lvalue. Here are some examples:
3658///  - &(x) => x
3659///  - &*****f => f for f a function designator.
3660///  - &s.xx => s
3661///  - &s.zz[1].yy -> s, if zz is an array
3662///  - *(x + 1) -> x, if x is an array
3663///  - &"123"[2] -> 0
3664///  - & __real__ x -> x
3665static NamedDecl *getPrimaryDecl(Expr *E) {
3666  switch (E->getStmtClass()) {
3667  case Stmt::DeclRefExprClass:
3668  case Stmt::QualifiedDeclRefExprClass:
3669    return cast<DeclRefExpr>(E)->getDecl();
3670  case Stmt::MemberExprClass:
3671    // Fields cannot be declared with a 'register' storage class.
3672    // &X->f is always ok, even if X is declared register.
3673    if (cast<MemberExpr>(E)->isArrow())
3674      return 0;
3675    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
3676  case Stmt::ArraySubscriptExprClass: {
3677    // &X[4] and &4[X] refers to X if X is not a pointer.
3678
3679    NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
3680    ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3681    if (!VD || VD->getType()->isPointerType())
3682      return 0;
3683    else
3684      return VD;
3685  }
3686  case Stmt::UnaryOperatorClass: {
3687    UnaryOperator *UO = cast<UnaryOperator>(E);
3688
3689    switch(UO->getOpcode()) {
3690    case UnaryOperator::Deref: {
3691      // *(X + 1) refers to X if X is not a pointer.
3692      if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3693        ValueDecl *VD = dyn_cast<ValueDecl>(D);
3694        if (!VD || VD->getType()->isPointerType())
3695          return 0;
3696        return VD;
3697      }
3698      return 0;
3699    }
3700    case UnaryOperator::Real:
3701    case UnaryOperator::Imag:
3702    case UnaryOperator::Extension:
3703      return getPrimaryDecl(UO->getSubExpr());
3704    default:
3705      return 0;
3706    }
3707  }
3708  case Stmt::BinaryOperatorClass: {
3709    BinaryOperator *BO = cast<BinaryOperator>(E);
3710
3711    // Handle cases involving pointer arithmetic. The result of an
3712    // Assign or AddAssign is not an lvalue so they can be ignored.
3713
3714    // (x + n) or (n + x) => x
3715    if (BO->getOpcode() == BinaryOperator::Add) {
3716      if (BO->getLHS()->getType()->isPointerType()) {
3717        return getPrimaryDecl(BO->getLHS());
3718      } else if (BO->getRHS()->getType()->isPointerType()) {
3719        return getPrimaryDecl(BO->getRHS());
3720      }
3721    }
3722
3723    return 0;
3724  }
3725  case Stmt::ParenExprClass:
3726    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
3727  case Stmt::ImplicitCastExprClass:
3728    // &X[4] when X is an array, has an implicit cast from array to pointer.
3729    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
3730  default:
3731    return 0;
3732  }
3733}
3734
3735/// CheckAddressOfOperand - The operand of & must be either a function
3736/// designator or an lvalue designating an object. If it is an lvalue, the
3737/// object cannot be declared with storage class register or be a bit field.
3738/// Note: The usual conversions are *not* applied to the operand of the &
3739/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
3740/// In C++, the operand might be an overloaded function name, in which case
3741/// we allow the '&' but retain the overloaded-function type.
3742QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
3743  if (op->isTypeDependent())
3744    return Context.DependentTy;
3745
3746  if (getLangOptions().C99) {
3747    // Implement C99-only parts of addressof rules.
3748    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3749      if (uOp->getOpcode() == UnaryOperator::Deref)
3750        // Per C99 6.5.3.2, the address of a deref always returns a valid result
3751        // (assuming the deref expression is valid).
3752        return uOp->getSubExpr()->getType();
3753    }
3754    // Technically, there should be a check for array subscript
3755    // expressions here, but the result of one is always an lvalue anyway.
3756  }
3757  NamedDecl *dcl = getPrimaryDecl(op);
3758  Expr::isLvalueResult lval = op->isLvalue(Context);
3759
3760  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
3761    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3762      // FIXME: emit more specific diag...
3763      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3764        << op->getSourceRange();
3765      return QualType();
3766    }
3767  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
3768    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3769      if (Field->isBitField()) {
3770        Diag(OpLoc, diag::err_typecheck_address_of)
3771          << "bit-field" << op->getSourceRange();
3772        return QualType();
3773      }
3774    }
3775  // Check for Apple extension for accessing vector components.
3776  } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3777           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
3778    Diag(OpLoc, diag::err_typecheck_address_of)
3779      << "vector element" << op->getSourceRange();
3780    return QualType();
3781  } else if (dcl) { // C99 6.5.3.2p1
3782    // We have an lvalue with a decl. Make sure the decl is not declared
3783    // with the register storage-class specifier.
3784    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3785      if (vd->getStorageClass() == VarDecl::Register) {
3786        Diag(OpLoc, diag::err_typecheck_address_of)
3787          << "register variable" << op->getSourceRange();
3788        return QualType();
3789      }
3790    } else if (isa<OverloadedFunctionDecl>(dcl)) {
3791      return Context.OverloadTy;
3792    } else if (isa<FieldDecl>(dcl)) {
3793      // Okay: we can take the address of a field.
3794      // Could be a pointer to member, though, if there is an explicit
3795      // scope qualifier for the class.
3796      if (isa<QualifiedDeclRefExpr>(op)) {
3797        DeclContext *Ctx = dcl->getDeclContext();
3798        if (Ctx && Ctx->isRecord())
3799          return Context.getMemberPointerType(op->getType(),
3800                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3801      }
3802    } else if (isa<FunctionDecl>(dcl)) {
3803      // Okay: we can take the address of a function.
3804      // As above.
3805      if (isa<QualifiedDeclRefExpr>(op)) {
3806        DeclContext *Ctx = dcl->getDeclContext();
3807        if (Ctx && Ctx->isRecord())
3808          return Context.getMemberPointerType(op->getType(),
3809                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3810      }
3811    }
3812    else
3813      assert(0 && "Unknown/unexpected decl type");
3814  }
3815
3816  // If the operand has type "type", the result has type "pointer to type".
3817  return Context.getPointerType(op->getType());
3818}
3819
3820QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3821  if (Op->isTypeDependent())
3822    return Context.DependentTy;
3823
3824  UsualUnaryConversions(Op);
3825  QualType Ty = Op->getType();
3826
3827  // Note that per both C89 and C99, this is always legal, even if ptype is an
3828  // incomplete type or void.  It would be possible to warn about dereferencing
3829  // a void pointer, but it's completely well-defined, and such a warning is
3830  // unlikely to catch any mistakes.
3831  if (const PointerType *PT = Ty->getAsPointerType())
3832    return PT->getPointeeType();
3833
3834  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
3835    << Ty << Op->getSourceRange();
3836  return QualType();
3837}
3838
3839static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3840  tok::TokenKind Kind) {
3841  BinaryOperator::Opcode Opc;
3842  switch (Kind) {
3843  default: assert(0 && "Unknown binop!");
3844  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
3845  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
3846  case tok::star:                 Opc = BinaryOperator::Mul; break;
3847  case tok::slash:                Opc = BinaryOperator::Div; break;
3848  case tok::percent:              Opc = BinaryOperator::Rem; break;
3849  case tok::plus:                 Opc = BinaryOperator::Add; break;
3850  case tok::minus:                Opc = BinaryOperator::Sub; break;
3851  case tok::lessless:             Opc = BinaryOperator::Shl; break;
3852  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
3853  case tok::lessequal:            Opc = BinaryOperator::LE; break;
3854  case tok::less:                 Opc = BinaryOperator::LT; break;
3855  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
3856  case tok::greater:              Opc = BinaryOperator::GT; break;
3857  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
3858  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
3859  case tok::amp:                  Opc = BinaryOperator::And; break;
3860  case tok::caret:                Opc = BinaryOperator::Xor; break;
3861  case tok::pipe:                 Opc = BinaryOperator::Or; break;
3862  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
3863  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
3864  case tok::equal:                Opc = BinaryOperator::Assign; break;
3865  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
3866  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
3867  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
3868  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
3869  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
3870  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
3871  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
3872  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
3873  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
3874  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
3875  case tok::comma:                Opc = BinaryOperator::Comma; break;
3876  }
3877  return Opc;
3878}
3879
3880static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3881  tok::TokenKind Kind) {
3882  UnaryOperator::Opcode Opc;
3883  switch (Kind) {
3884  default: assert(0 && "Unknown unary op!");
3885  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
3886  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
3887  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
3888  case tok::star:         Opc = UnaryOperator::Deref; break;
3889  case tok::plus:         Opc = UnaryOperator::Plus; break;
3890  case tok::minus:        Opc = UnaryOperator::Minus; break;
3891  case tok::tilde:        Opc = UnaryOperator::Not; break;
3892  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
3893  case tok::kw___real:    Opc = UnaryOperator::Real; break;
3894  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
3895  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3896  }
3897  return Opc;
3898}
3899
3900/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3901/// operator @p Opc at location @c TokLoc. This routine only supports
3902/// built-in operations; ActOnBinOp handles overloaded operators.
3903Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3904                                                  unsigned Op,
3905                                                  Expr *lhs, Expr *rhs) {
3906  QualType ResultTy;  // Result type of the binary operator.
3907  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
3908  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3909
3910  switch (Opc) {
3911  case BinaryOperator::Assign:
3912    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3913    break;
3914  case BinaryOperator::PtrMemD:
3915  case BinaryOperator::PtrMemI:
3916    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3917                                            Opc == BinaryOperator::PtrMemI);
3918    break;
3919  case BinaryOperator::Mul:
3920  case BinaryOperator::Div:
3921    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3922    break;
3923  case BinaryOperator::Rem:
3924    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3925    break;
3926  case BinaryOperator::Add:
3927    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3928    break;
3929  case BinaryOperator::Sub:
3930    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3931    break;
3932  case BinaryOperator::Shl:
3933  case BinaryOperator::Shr:
3934    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3935    break;
3936  case BinaryOperator::LE:
3937  case BinaryOperator::LT:
3938  case BinaryOperator::GE:
3939  case BinaryOperator::GT:
3940    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3941    break;
3942  case BinaryOperator::EQ:
3943  case BinaryOperator::NE:
3944    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3945    break;
3946  case BinaryOperator::And:
3947  case BinaryOperator::Xor:
3948  case BinaryOperator::Or:
3949    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3950    break;
3951  case BinaryOperator::LAnd:
3952  case BinaryOperator::LOr:
3953    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3954    break;
3955  case BinaryOperator::MulAssign:
3956  case BinaryOperator::DivAssign:
3957    CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3958    if (!CompTy.isNull())
3959      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3960    break;
3961  case BinaryOperator::RemAssign:
3962    CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3963    if (!CompTy.isNull())
3964      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3965    break;
3966  case BinaryOperator::AddAssign:
3967    CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3968    if (!CompTy.isNull())
3969      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3970    break;
3971  case BinaryOperator::SubAssign:
3972    CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3973    if (!CompTy.isNull())
3974      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3975    break;
3976  case BinaryOperator::ShlAssign:
3977  case BinaryOperator::ShrAssign:
3978    CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3979    if (!CompTy.isNull())
3980      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3981    break;
3982  case BinaryOperator::AndAssign:
3983  case BinaryOperator::XorAssign:
3984  case BinaryOperator::OrAssign:
3985    CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3986    if (!CompTy.isNull())
3987      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3988    break;
3989  case BinaryOperator::Comma:
3990    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3991    break;
3992  }
3993  if (ResultTy.isNull())
3994    return ExprError();
3995  if (CompTy.isNull())
3996    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3997  else
3998    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
3999                                                      CompTy, OpLoc));
4000}
4001
4002// Binary Operators.  'Tok' is the token for the operator.
4003Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4004                                          tok::TokenKind Kind,
4005                                          ExprArg LHS, ExprArg RHS) {
4006  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
4007  Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
4008
4009  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4010  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
4011
4012  if (getLangOptions().CPlusPlus &&
4013      (lhs->getType()->isOverloadableType() ||
4014       rhs->getType()->isOverloadableType())) {
4015    // Find all of the overloaded operators visible from this
4016    // point. We perform both an operator-name lookup from the local
4017    // scope and an argument-dependent lookup based on the types of
4018    // the arguments.
4019    FunctionSet Functions;
4020    OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4021    if (OverOp != OO_None) {
4022      LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4023                                   Functions);
4024      Expr *Args[2] = { lhs, rhs };
4025      DeclarationName OpName
4026        = Context.DeclarationNames.getCXXOperatorName(OverOp);
4027      ArgumentDependentLookup(OpName, Args, 2, Functions);
4028    }
4029
4030    // Build the (potentially-overloaded, potentially-dependent)
4031    // binary operation.
4032    return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
4033  }
4034
4035  // Build a built-in binary operation.
4036  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
4037}
4038
4039Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4040                                                    unsigned OpcIn,
4041                                                    ExprArg InputArg) {
4042  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4043
4044  // FIXME: Input is modified below, but InputArg is not updated
4045  // appropriately.
4046  Expr *Input = (Expr *)InputArg.get();
4047  QualType resultType;
4048  switch (Opc) {
4049  case UnaryOperator::PostInc:
4050  case UnaryOperator::PostDec:
4051  case UnaryOperator::OffsetOf:
4052    assert(false && "Invalid unary operator");
4053    break;
4054
4055  case UnaryOperator::PreInc:
4056  case UnaryOperator::PreDec:
4057    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4058                                                Opc == UnaryOperator::PreInc);
4059    break;
4060  case UnaryOperator::AddrOf:
4061    resultType = CheckAddressOfOperand(Input, OpLoc);
4062    break;
4063  case UnaryOperator::Deref:
4064    DefaultFunctionArrayConversion(Input);
4065    resultType = CheckIndirectionOperand(Input, OpLoc);
4066    break;
4067  case UnaryOperator::Plus:
4068  case UnaryOperator::Minus:
4069    UsualUnaryConversions(Input);
4070    resultType = Input->getType();
4071    if (resultType->isDependentType())
4072      break;
4073    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4074      break;
4075    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4076             resultType->isEnumeralType())
4077      break;
4078    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4079             Opc == UnaryOperator::Plus &&
4080             resultType->isPointerType())
4081      break;
4082
4083    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4084      << resultType << Input->getSourceRange());
4085  case UnaryOperator::Not: // bitwise complement
4086    UsualUnaryConversions(Input);
4087    resultType = Input->getType();
4088    if (resultType->isDependentType())
4089      break;
4090    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4091    if (resultType->isComplexType() || resultType->isComplexIntegerType())
4092      // C99 does not support '~' for complex conjugation.
4093      Diag(OpLoc, diag::ext_integer_complement_complex)
4094        << resultType << Input->getSourceRange();
4095    else if (!resultType->isIntegerType())
4096      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4097        << resultType << Input->getSourceRange());
4098    break;
4099  case UnaryOperator::LNot: // logical negation
4100    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4101    DefaultFunctionArrayConversion(Input);
4102    resultType = Input->getType();
4103    if (resultType->isDependentType())
4104      break;
4105    if (!resultType->isScalarType()) // C99 6.5.3.3p1
4106      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4107        << resultType << Input->getSourceRange());
4108    // LNot always has type int. C99 6.5.3.3p5.
4109    // In C++, it's bool. C++ 5.3.1p8
4110    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
4111    break;
4112  case UnaryOperator::Real:
4113  case UnaryOperator::Imag:
4114    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
4115    break;
4116  case UnaryOperator::Extension:
4117    resultType = Input->getType();
4118    break;
4119  }
4120  if (resultType.isNull())
4121    return ExprError();
4122
4123  InputArg.release();
4124  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
4125}
4126
4127// Unary Operators.  'Tok' is the token for the operator.
4128Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4129                                            tok::TokenKind Op, ExprArg input) {
4130  Expr *Input = (Expr*)input.get();
4131  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4132
4133  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4134    // Find all of the overloaded operators visible from this
4135    // point. We perform both an operator-name lookup from the local
4136    // scope and an argument-dependent lookup based on the types of
4137    // the arguments.
4138    FunctionSet Functions;
4139    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4140    if (OverOp != OO_None) {
4141      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4142                                   Functions);
4143      DeclarationName OpName
4144        = Context.DeclarationNames.getCXXOperatorName(OverOp);
4145      ArgumentDependentLookup(OpName, &Input, 1, Functions);
4146    }
4147
4148    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4149  }
4150
4151  return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4152}
4153
4154/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4155Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4156                                            SourceLocation LabLoc,
4157                                            IdentifierInfo *LabelII) {
4158  // Look up the record for this label identifier.
4159  LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4160                                     LabelMap[LabelII];
4161
4162  // If we haven't seen this label yet, create a forward reference. It
4163  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
4164  if (LabelDecl == 0)
4165    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
4166
4167  // Create the AST node.  The address of a label always has type 'void*'.
4168  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4169                                       Context.getPointerType(Context.VoidTy)));
4170}
4171
4172Sema::OwningExprResult
4173Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4174                    SourceLocation RPLoc) { // "({..})"
4175  Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
4176  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4177  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4178
4179  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4180  if (isFileScope) {
4181    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
4182  }
4183
4184  // FIXME: there are a variety of strange constraints to enforce here, for
4185  // example, it is not possible to goto into a stmt expression apparently.
4186  // More semantic analysis is needed.
4187
4188  // FIXME: the last statement in the compount stmt has its value used.  We
4189  // should not warn about it being unused.
4190
4191  // If there are sub stmts in the compound stmt, take the type of the last one
4192  // as the type of the stmtexpr.
4193  QualType Ty = Context.VoidTy;
4194
4195  if (!Compound->body_empty()) {
4196    Stmt *LastStmt = Compound->body_back();
4197    // If LastStmt is a label, skip down through into the body.
4198    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4199      LastStmt = Label->getSubStmt();
4200
4201    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
4202      Ty = LastExpr->getType();
4203  }
4204
4205  substmt.release();
4206  return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
4207}
4208
4209Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4210                                                  SourceLocation BuiltinLoc,
4211                                                  SourceLocation TypeLoc,
4212                                                  TypeTy *argty,
4213                                                  OffsetOfComponent *CompPtr,
4214                                                  unsigned NumComponents,
4215                                                  SourceLocation RPLoc) {
4216  // FIXME: This function leaks all expressions in the offset components on
4217  // error.
4218  QualType ArgTy = QualType::getFromOpaquePtr(argty);
4219  assert(!ArgTy.isNull() && "Missing type argument!");
4220
4221  bool Dependent = ArgTy->isDependentType();
4222
4223  // We must have at least one component that refers to the type, and the first
4224  // one is known to be a field designator.  Verify that the ArgTy represents
4225  // a struct/union/class.
4226  if (!Dependent && !ArgTy->isRecordType())
4227    return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
4228
4229  // FIXME: Does the type need to be complete?
4230
4231  // Otherwise, create a null pointer as the base, and iteratively process
4232  // the offsetof designators.
4233  QualType ArgTyPtr = Context.getPointerType(ArgTy);
4234  Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
4235  Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
4236                                    ArgTy, SourceLocation());
4237
4238  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4239  // GCC extension, diagnose them.
4240  // FIXME: This diagnostic isn't actually visible because the location is in
4241  // a system header!
4242  if (NumComponents != 1)
4243    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4244      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
4245
4246  if (!Dependent) {
4247    // FIXME: Dependent case loses a lot of information here. And probably
4248    // leaks like a sieve.
4249    for (unsigned i = 0; i != NumComponents; ++i) {
4250      const OffsetOfComponent &OC = CompPtr[i];
4251      if (OC.isBrackets) {
4252        // Offset of an array sub-field.  TODO: Should we allow vector elements?
4253        const ArrayType *AT = Context.getAsArrayType(Res->getType());
4254        if (!AT) {
4255          Res->Destroy(Context);
4256          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4257            << Res->getType());
4258        }
4259
4260        // FIXME: C++: Verify that operator[] isn't overloaded.
4261
4262        // Promote the array so it looks more like a normal array subscript
4263        // expression.
4264        DefaultFunctionArrayConversion(Res);
4265
4266        // C99 6.5.2.1p1
4267        Expr *Idx = static_cast<Expr*>(OC.U.E);
4268        // FIXME: Leaks Res
4269        if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4270          return ExprError(Diag(Idx->getLocStart(),
4271                                diag::err_typecheck_subscript)
4272            << Idx->getSourceRange());
4273
4274        Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4275                                               OC.LocEnd);
4276        continue;
4277      }
4278
4279      const RecordType *RC = Res->getType()->getAsRecordType();
4280      if (!RC) {
4281        Res->Destroy(Context);
4282        return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4283          << Res->getType());
4284      }
4285
4286      // Get the decl corresponding to this.
4287      RecordDecl *RD = RC->getDecl();
4288      FieldDecl *MemberDecl
4289        = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4290                                                          LookupMemberName)
4291                                        .getAsDecl());
4292      // FIXME: Leaks Res
4293      if (!MemberDecl)
4294        return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4295         << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
4296
4297      // FIXME: C++: Verify that MemberDecl isn't a static field.
4298      // FIXME: Verify that MemberDecl isn't a bitfield.
4299      // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4300      // matter here.
4301      Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4302                                   MemberDecl->getType().getNonReferenceType());
4303    }
4304  }
4305
4306  return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4307                                           Context.getSizeType(), BuiltinLoc));
4308}
4309
4310
4311Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4312                                                      TypeTy *arg1,TypeTy *arg2,
4313                                                      SourceLocation RPLoc) {
4314  QualType argT1 = QualType::getFromOpaquePtr(arg1);
4315  QualType argT2 = QualType::getFromOpaquePtr(arg2);
4316
4317  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4318
4319  return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4320                                                 argT1, argT2, RPLoc));
4321}
4322
4323Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4324                                             ExprArg cond,
4325                                             ExprArg expr1, ExprArg expr2,
4326                                             SourceLocation RPLoc) {
4327  Expr *CondExpr = static_cast<Expr*>(cond.get());
4328  Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4329  Expr *RHSExpr = static_cast<Expr*>(expr2.get());
4330
4331  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4332
4333  QualType resType;
4334  if (CondExpr->isValueDependent()) {
4335    resType = Context.DependentTy;
4336  } else {
4337    // The conditional expression is required to be a constant expression.
4338    llvm::APSInt condEval(32);
4339    SourceLocation ExpLoc;
4340    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4341      return ExprError(Diag(ExpLoc,
4342                       diag::err_typecheck_choose_expr_requires_constant)
4343        << CondExpr->getSourceRange());
4344
4345    // If the condition is > zero, then the AST type is the same as the LSHExpr.
4346    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4347  }
4348
4349  cond.release(); expr1.release(); expr2.release();
4350  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4351                                        resType, RPLoc));
4352}
4353
4354//===----------------------------------------------------------------------===//
4355// Clang Extensions.
4356//===----------------------------------------------------------------------===//
4357
4358/// ActOnBlockStart - This callback is invoked when a block literal is started.
4359void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
4360  // Analyze block parameters.
4361  BlockSemaInfo *BSI = new BlockSemaInfo();
4362
4363  // Add BSI to CurBlock.
4364  BSI->PrevBlockInfo = CurBlock;
4365  CurBlock = BSI;
4366
4367  BSI->ReturnType = 0;
4368  BSI->TheScope = BlockScope;
4369  BSI->hasBlockDeclRefExprs = false;
4370
4371  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
4372  PushDeclContext(BlockScope, BSI->TheDecl);
4373}
4374
4375void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4376  assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4377
4378  if (ParamInfo.getNumTypeObjects() == 0
4379      || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4380    QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4381
4382    // The type is entirely optional as well, if none, use DependentTy.
4383    if (T.isNull())
4384      T = Context.DependentTy;
4385
4386    // The parameter list is optional, if there was none, assume ().
4387    if (!T->isFunctionType())
4388      T = Context.getFunctionType(T, NULL, 0, 0, 0);
4389
4390    CurBlock->hasPrototype = true;
4391    CurBlock->isVariadic = false;
4392    Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4393      .getTypePtr();
4394
4395    if (!RetTy->isDependentType())
4396      CurBlock->ReturnType = RetTy;
4397    return;
4398  }
4399
4400  // Analyze arguments to block.
4401  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4402         "Not a function declarator!");
4403  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4404
4405  CurBlock->hasPrototype = FTI.hasPrototype;
4406  CurBlock->isVariadic = true;
4407
4408  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4409  // no arguments, not a function that takes a single void argument.
4410  if (FTI.hasPrototype &&
4411      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4412      (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4413        ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4414    // empty arg list, don't push any params.
4415    CurBlock->isVariadic = false;
4416  } else if (FTI.hasPrototype) {
4417    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
4418      CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4419    CurBlock->isVariadic = FTI.isVariadic;
4420    QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4421
4422    Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4423      .getTypePtr();
4424
4425    if (!RetTy->isDependentType())
4426      CurBlock->ReturnType = RetTy;
4427  }
4428  CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
4429                                        CurBlock->Params.size());
4430
4431  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4432       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4433    // If this has an identifier, add it to the scope stack.
4434    if ((*AI)->getIdentifier())
4435      PushOnScopeChains(*AI, CurBlock->TheScope);
4436}
4437
4438/// ActOnBlockError - If there is an error parsing a block, this callback
4439/// is invoked to pop the information about the block from the action impl.
4440void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4441  // Ensure that CurBlock is deleted.
4442  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4443
4444  // Pop off CurBlock, handle nested blocks.
4445  CurBlock = CurBlock->PrevBlockInfo;
4446
4447  // FIXME: Delete the ParmVarDecl objects as well???
4448
4449}
4450
4451/// ActOnBlockStmtExpr - This is called when the body of a block statement
4452/// literal was successfully completed.  ^(int x){...}
4453Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4454                                                StmtArg body, Scope *CurScope) {
4455  // Ensure that CurBlock is deleted.
4456  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4457
4458  PopDeclContext();
4459
4460  // Pop off CurBlock, handle nested blocks.
4461  CurBlock = CurBlock->PrevBlockInfo;
4462
4463  QualType RetTy = Context.VoidTy;
4464  if (BSI->ReturnType)
4465    RetTy = QualType(BSI->ReturnType, 0);
4466
4467  llvm::SmallVector<QualType, 8> ArgTypes;
4468  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4469    ArgTypes.push_back(BSI->Params[i]->getType());
4470
4471  QualType BlockTy;
4472  if (!BSI->hasPrototype)
4473    BlockTy = Context.getFunctionNoProtoType(RetTy);
4474  else
4475    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
4476                                      BSI->isVariadic, 0);
4477
4478  BlockTy = Context.getBlockPointerType(BlockTy);
4479
4480  BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4481  return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4482                                       BSI->hasBlockDeclRefExprs));
4483}
4484
4485Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4486                                        ExprArg expr, TypeTy *type,
4487                                        SourceLocation RPLoc) {
4488  QualType T = QualType::getFromOpaquePtr(type);
4489
4490  InitBuiltinVaListType();
4491
4492  // Get the va_list type
4493  QualType VaListType = Context.getBuiltinVaListType();
4494  // Deal with implicit array decay; for example, on x86-64,
4495  // va_list is an array, but it's supposed to decay to
4496  // a pointer for va_arg.
4497  if (VaListType->isArrayType())
4498    VaListType = Context.getArrayDecayedType(VaListType);
4499  // Make sure the input expression also decays appropriately.
4500  Expr *E = static_cast<Expr*>(expr.get());
4501  UsualUnaryConversions(E);
4502
4503  if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
4504    return ExprError(Diag(E->getLocStart(),
4505                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
4506      << E->getType() << E->getSourceRange());
4507
4508  // FIXME: Warn if a non-POD type is passed in.
4509
4510  expr.release();
4511  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4512                                       RPLoc));
4513}
4514
4515Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4516  // The type of __null will be int or long, depending on the size of
4517  // pointers on the target.
4518  QualType Ty;
4519  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4520    Ty = Context.IntTy;
4521  else
4522    Ty = Context.LongTy;
4523
4524  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
4525}
4526
4527bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4528                                    SourceLocation Loc,
4529                                    QualType DstType, QualType SrcType,
4530                                    Expr *SrcExpr, const char *Flavor) {
4531  // Decode the result (notice that AST's are still created for extensions).
4532  bool isInvalid = false;
4533  unsigned DiagKind;
4534  switch (ConvTy) {
4535  default: assert(0 && "Unknown conversion type");
4536  case Compatible: return false;
4537  case PointerToInt:
4538    DiagKind = diag::ext_typecheck_convert_pointer_int;
4539    break;
4540  case IntToPointer:
4541    DiagKind = diag::ext_typecheck_convert_int_pointer;
4542    break;
4543  case IncompatiblePointer:
4544    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4545    break;
4546  case FunctionVoidPointer:
4547    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4548    break;
4549  case CompatiblePointerDiscardsQualifiers:
4550    // If the qualifiers lost were because we were applying the
4551    // (deprecated) C++ conversion from a string literal to a char*
4552    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
4553    // Ideally, this check would be performed in
4554    // CheckPointerTypesForAssignment. However, that would require a
4555    // bit of refactoring (so that the second argument is an
4556    // expression, rather than a type), which should be done as part
4557    // of a larger effort to fix CheckPointerTypesForAssignment for
4558    // C++ semantics.
4559    if (getLangOptions().CPlusPlus &&
4560        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4561      return false;
4562    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4563    break;
4564  case IntToBlockPointer:
4565    DiagKind = diag::err_int_to_block_pointer;
4566    break;
4567  case IncompatibleBlockPointer:
4568    DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
4569    break;
4570  case IncompatibleObjCQualifiedId:
4571    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4572    // it can give a more specific diagnostic.
4573    DiagKind = diag::warn_incompatible_qualified_id;
4574    break;
4575  case IncompatibleVectors:
4576    DiagKind = diag::warn_incompatible_vectors;
4577    break;
4578  case Incompatible:
4579    DiagKind = diag::err_typecheck_convert_incompatible;
4580    isInvalid = true;
4581    break;
4582  }
4583
4584  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4585    << SrcExpr->getSourceRange();
4586  return isInvalid;
4587}
4588
4589bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4590{
4591  Expr::EvalResult EvalResult;
4592
4593  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4594      EvalResult.HasSideEffects) {
4595    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4596
4597    if (EvalResult.Diag) {
4598      // We only show the note if it's not the usual "invalid subexpression"
4599      // or if it's actually in a subexpression.
4600      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4601          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4602        Diag(EvalResult.DiagLoc, EvalResult.Diag);
4603    }
4604
4605    return true;
4606  }
4607
4608  if (EvalResult.Diag) {
4609    Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4610      E->getSourceRange();
4611
4612    // Print the reason it's not a constant.
4613    if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4614      Diag(EvalResult.DiagLoc, EvalResult.Diag);
4615  }
4616
4617  if (Result)
4618    *Result = EvalResult.Val.getInt();
4619  return false;
4620}
4621