SemaChecking.cpp revision bbcb7ea8a062a8f1d5cb504e4518a5d4fbab873a
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
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 extra semantic analysis beyond what is enforced
11//  by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Sema.h"
17#include "clang/Sema/SemaInternal.h"
18#include "clang/Sema/ScopeInfo.h"
19#include "clang/Analysis/Analyses/FormatString.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/CharUnits.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/EvaluatedExprVisitor.h"
27#include "clang/AST/DeclObjC.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
30#include "clang/Lex/Preprocessor.h"
31#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/Support/raw_ostream.h"
34#include "clang/Basic/TargetBuiltins.h"
35#include "clang/Basic/TargetInfo.h"
36#include "clang/Basic/ConvertUTF.h"
37#include <limits>
38using namespace clang;
39using namespace sema;
40
41SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
42                                                    unsigned ByteNo) const {
43  return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
44                               PP.getLangOptions(), PP.getTargetInfo());
45}
46
47
48/// CheckablePrintfAttr - does a function call have a "printf" attribute
49/// and arguments that merit checking?
50bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
51  if (Format->getType() == "printf") return true;
52  if (Format->getType() == "printf0") {
53    // printf0 allows null "format" string; if so don't check format/args
54    unsigned format_idx = Format->getFormatIdx() - 1;
55    // Does the index refer to the implicit object argument?
56    if (isa<CXXMemberCallExpr>(TheCall)) {
57      if (format_idx == 0)
58        return false;
59      --format_idx;
60    }
61    if (format_idx < TheCall->getNumArgs()) {
62      Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
63      if (!Format->isNullPointerConstant(Context,
64                                         Expr::NPC_ValueDependentIsNull))
65        return true;
66    }
67  }
68  return false;
69}
70
71/// Checks that a call expression's argument count is the desired number.
72/// This is useful when doing custom type-checking.  Returns true on error.
73static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
74  unsigned argCount = call->getNumArgs();
75  if (argCount == desiredArgCount) return false;
76
77  if (argCount < desiredArgCount)
78    return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
79        << 0 /*function call*/ << desiredArgCount << argCount
80        << call->getSourceRange();
81
82  // Highlight all the excess arguments.
83  SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
84                    call->getArg(argCount - 1)->getLocEnd());
85
86  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
87    << 0 /*function call*/ << desiredArgCount << argCount
88    << call->getArg(1)->getSourceRange();
89}
90
91ExprResult
92Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
93  ExprResult TheCallResult(Owned(TheCall));
94
95  // Find out if any arguments are required to be integer constant expressions.
96  unsigned ICEArguments = 0;
97  ASTContext::GetBuiltinTypeError Error;
98  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
99  if (Error != ASTContext::GE_None)
100    ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
101
102  // If any arguments are required to be ICE's, check and diagnose.
103  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
104    // Skip arguments not required to be ICE's.
105    if ((ICEArguments & (1 << ArgNo)) == 0) continue;
106
107    llvm::APSInt Result;
108    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
109      return true;
110    ICEArguments &= ~(1 << ArgNo);
111  }
112
113  switch (BuiltinID) {
114  case Builtin::BI__builtin___CFStringMakeConstantString:
115    assert(TheCall->getNumArgs() == 1 &&
116           "Wrong # arguments to builtin CFStringMakeConstantString");
117    if (CheckObjCString(TheCall->getArg(0)))
118      return ExprError();
119    break;
120  case Builtin::BI__builtin_stdarg_start:
121  case Builtin::BI__builtin_va_start:
122    if (SemaBuiltinVAStart(TheCall))
123      return ExprError();
124    break;
125  case Builtin::BI__builtin_isgreater:
126  case Builtin::BI__builtin_isgreaterequal:
127  case Builtin::BI__builtin_isless:
128  case Builtin::BI__builtin_islessequal:
129  case Builtin::BI__builtin_islessgreater:
130  case Builtin::BI__builtin_isunordered:
131    if (SemaBuiltinUnorderedCompare(TheCall))
132      return ExprError();
133    break;
134  case Builtin::BI__builtin_fpclassify:
135    if (SemaBuiltinFPClassification(TheCall, 6))
136      return ExprError();
137    break;
138  case Builtin::BI__builtin_isfinite:
139  case Builtin::BI__builtin_isinf:
140  case Builtin::BI__builtin_isinf_sign:
141  case Builtin::BI__builtin_isnan:
142  case Builtin::BI__builtin_isnormal:
143    if (SemaBuiltinFPClassification(TheCall, 1))
144      return ExprError();
145    break;
146  case Builtin::BI__builtin_shufflevector:
147    return SemaBuiltinShuffleVector(TheCall);
148    // TheCall will be freed by the smart pointer here, but that's fine, since
149    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
150  case Builtin::BI__builtin_prefetch:
151    if (SemaBuiltinPrefetch(TheCall))
152      return ExprError();
153    break;
154  case Builtin::BI__builtin_object_size:
155    if (SemaBuiltinObjectSize(TheCall))
156      return ExprError();
157    break;
158  case Builtin::BI__builtin_longjmp:
159    if (SemaBuiltinLongjmp(TheCall))
160      return ExprError();
161    break;
162
163  case Builtin::BI__builtin_classify_type:
164    if (checkArgCount(*this, TheCall, 1)) return true;
165    TheCall->setType(Context.IntTy);
166    break;
167  case Builtin::BI__builtin_constant_p:
168    if (checkArgCount(*this, TheCall, 1)) return true;
169    TheCall->setType(Context.IntTy);
170    break;
171  case Builtin::BI__sync_fetch_and_add:
172  case Builtin::BI__sync_fetch_and_sub:
173  case Builtin::BI__sync_fetch_and_or:
174  case Builtin::BI__sync_fetch_and_and:
175  case Builtin::BI__sync_fetch_and_xor:
176  case Builtin::BI__sync_add_and_fetch:
177  case Builtin::BI__sync_sub_and_fetch:
178  case Builtin::BI__sync_and_and_fetch:
179  case Builtin::BI__sync_or_and_fetch:
180  case Builtin::BI__sync_xor_and_fetch:
181  case Builtin::BI__sync_val_compare_and_swap:
182  case Builtin::BI__sync_bool_compare_and_swap:
183  case Builtin::BI__sync_lock_test_and_set:
184  case Builtin::BI__sync_lock_release:
185  case Builtin::BI__sync_swap:
186    return SemaBuiltinAtomicOverloaded(move(TheCallResult));
187  }
188
189  // Since the target specific builtins for each arch overlap, only check those
190  // of the arch we are compiling for.
191  if (BuiltinID >= Builtin::FirstTSBuiltin) {
192    switch (Context.getTargetInfo().getTriple().getArch()) {
193      case llvm::Triple::arm:
194      case llvm::Triple::thumb:
195        if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
196          return ExprError();
197        break;
198      default:
199        break;
200    }
201  }
202
203  return move(TheCallResult);
204}
205
206// Get the valid immediate range for the specified NEON type code.
207static unsigned RFT(unsigned t, bool shift = false) {
208  bool quad = t & 0x10;
209
210  switch (t & 0x7) {
211    case 0: // i8
212      return shift ? 7 : (8 << (int)quad) - 1;
213    case 1: // i16
214      return shift ? 15 : (4 << (int)quad) - 1;
215    case 2: // i32
216      return shift ? 31 : (2 << (int)quad) - 1;
217    case 3: // i64
218      return shift ? 63 : (1 << (int)quad) - 1;
219    case 4: // f32
220      assert(!shift && "cannot shift float types!");
221      return (2 << (int)quad) - 1;
222    case 5: // poly8
223      return shift ? 7 : (8 << (int)quad) - 1;
224    case 6: // poly16
225      return shift ? 15 : (4 << (int)quad) - 1;
226    case 7: // float16
227      assert(!shift && "cannot shift float types!");
228      return (4 << (int)quad) - 1;
229  }
230  return 0;
231}
232
233bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
234  llvm::APSInt Result;
235
236  unsigned mask = 0;
237  unsigned TV = 0;
238  switch (BuiltinID) {
239#define GET_NEON_OVERLOAD_CHECK
240#include "clang/Basic/arm_neon.inc"
241#undef GET_NEON_OVERLOAD_CHECK
242  }
243
244  // For NEON intrinsics which are overloaded on vector element type, validate
245  // the immediate which specifies which variant to emit.
246  if (mask) {
247    unsigned ArgNo = TheCall->getNumArgs()-1;
248    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
249      return true;
250
251    TV = Result.getLimitedValue(32);
252    if ((TV > 31) || (mask & (1 << TV)) == 0)
253      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
254        << TheCall->getArg(ArgNo)->getSourceRange();
255  }
256
257  // For NEON intrinsics which take an immediate value as part of the
258  // instruction, range check them here.
259  unsigned i = 0, l = 0, u = 0;
260  switch (BuiltinID) {
261  default: return false;
262  case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
263  case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
264  case ARM::BI__builtin_arm_vcvtr_f:
265  case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
266#define GET_NEON_IMMEDIATE_CHECK
267#include "clang/Basic/arm_neon.inc"
268#undef GET_NEON_IMMEDIATE_CHECK
269  };
270
271  // Check that the immediate argument is actually a constant.
272  if (SemaBuiltinConstantArg(TheCall, i, Result))
273    return true;
274
275  // Range check against the upper/lower values for this isntruction.
276  unsigned Val = Result.getZExtValue();
277  if (Val < l || Val > (u + l))
278    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
279      << l << u+l << TheCall->getArg(i)->getSourceRange();
280
281  // FIXME: VFP Intrinsics should error if VFP not present.
282  return false;
283}
284
285/// CheckFunctionCall - Check a direct function call for various correctness
286/// and safety properties not strictly enforced by the C type system.
287bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
288  // Get the IdentifierInfo* for the called function.
289  IdentifierInfo *FnInfo = FDecl->getIdentifier();
290
291  // None of the checks below are needed for functions that don't have
292  // simple names (e.g., C++ conversion functions).
293  if (!FnInfo)
294    return false;
295
296  // FIXME: This mechanism should be abstracted to be less fragile and
297  // more efficient. For example, just map function ids to custom
298  // handlers.
299
300  // Printf and scanf checking.
301  for (specific_attr_iterator<FormatAttr>
302         i = FDecl->specific_attr_begin<FormatAttr>(),
303         e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
304
305    const FormatAttr *Format = *i;
306    const bool b = Format->getType() == "scanf";
307    if (b || CheckablePrintfAttr(Format, TheCall)) {
308      bool HasVAListArg = Format->getFirstArg() == 0;
309      CheckPrintfScanfArguments(TheCall, HasVAListArg,
310                                Format->getFormatIdx() - 1,
311                                HasVAListArg ? 0 : Format->getFirstArg() - 1,
312                                !b);
313    }
314  }
315
316  for (specific_attr_iterator<NonNullAttr>
317         i = FDecl->specific_attr_begin<NonNullAttr>(),
318         e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
319    CheckNonNullArguments(*i, TheCall->getArgs(),
320                          TheCall->getCallee()->getLocStart());
321  }
322
323  // Builtin handling
324  int CMF = -1;
325  switch (FDecl->getBuiltinID()) {
326  case Builtin::BI__builtin_memset:
327  case Builtin::BI__builtin___memset_chk:
328  case Builtin::BImemset:
329    CMF = CMF_Memset;
330    break;
331
332  case Builtin::BI__builtin_memcpy:
333  case Builtin::BI__builtin___memcpy_chk:
334  case Builtin::BImemcpy:
335    CMF = CMF_Memcpy;
336    break;
337
338  case Builtin::BI__builtin_memmove:
339  case Builtin::BI__builtin___memmove_chk:
340  case Builtin::BImemmove:
341    CMF = CMF_Memmove;
342    break;
343
344  case Builtin::BIstrlcpy:
345  case Builtin::BIstrlcat:
346    CheckStrlcpycatArguments(TheCall, FnInfo);
347    break;
348
349  case Builtin::BI__builtin_memcmp:
350    CMF = CMF_Memcmp;
351    break;
352
353  default:
354    if (FDecl->getLinkage() == ExternalLinkage &&
355        (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
356      if (FnInfo->isStr("memset"))
357        CMF = CMF_Memset;
358      else if (FnInfo->isStr("memcpy"))
359        CMF = CMF_Memcpy;
360      else if (FnInfo->isStr("memmove"))
361        CMF = CMF_Memmove;
362      else if (FnInfo->isStr("memcmp"))
363        CMF = CMF_Memcmp;
364    }
365    break;
366  }
367
368  // Memset/memcpy/memmove handling
369  if (CMF != -1)
370    CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
371
372  return false;
373}
374
375bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
376  // Printf checking.
377  const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
378  if (!Format)
379    return false;
380
381  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
382  if (!V)
383    return false;
384
385  QualType Ty = V->getType();
386  if (!Ty->isBlockPointerType())
387    return false;
388
389  const bool b = Format->getType() == "scanf";
390  if (!b && !CheckablePrintfAttr(Format, TheCall))
391    return false;
392
393  bool HasVAListArg = Format->getFirstArg() == 0;
394  CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
395                            HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
396
397  return false;
398}
399
400/// checkBuiltinArgument - Given a call to a builtin function, perform
401/// normal type-checking on the given argument, updating the call in
402/// place.  This is useful when a builtin function requires custom
403/// type-checking for some of its arguments but not necessarily all of
404/// them.
405///
406/// Returns true on error.
407static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
408  FunctionDecl *Fn = E->getDirectCallee();
409  assert(Fn && "builtin call without direct callee!");
410
411  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
412  InitializedEntity Entity =
413    InitializedEntity::InitializeParameter(S.Context, Param);
414
415  ExprResult Arg = E->getArg(0);
416  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
417  if (Arg.isInvalid())
418    return true;
419
420  E->setArg(ArgIndex, Arg.take());
421  return false;
422}
423
424/// SemaBuiltinAtomicOverloaded - We have a call to a function like
425/// __sync_fetch_and_add, which is an overloaded function based on the pointer
426/// type of its first argument.  The main ActOnCallExpr routines have already
427/// promoted the types of arguments because all of these calls are prototyped as
428/// void(...).
429///
430/// This function goes through and does final semantic checking for these
431/// builtins,
432ExprResult
433Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
434  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
435  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
436  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
437
438  // Ensure that we have at least one argument to do type inference from.
439  if (TheCall->getNumArgs() < 1) {
440    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
441      << 0 << 1 << TheCall->getNumArgs()
442      << TheCall->getCallee()->getSourceRange();
443    return ExprError();
444  }
445
446  // Inspect the first argument of the atomic builtin.  This should always be
447  // a pointer type, whose element is an integral scalar or pointer type.
448  // Because it is a pointer type, we don't have to worry about any implicit
449  // casts here.
450  // FIXME: We don't allow floating point scalars as input.
451  Expr *FirstArg = TheCall->getArg(0);
452  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
453  if (!pointerType) {
454    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
455      << FirstArg->getType() << FirstArg->getSourceRange();
456    return ExprError();
457  }
458
459  QualType ValType = pointerType->getPointeeType();
460  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
461      !ValType->isBlockPointerType()) {
462    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
463      << FirstArg->getType() << FirstArg->getSourceRange();
464    return ExprError();
465  }
466
467  switch (ValType.getObjCLifetime()) {
468  case Qualifiers::OCL_None:
469  case Qualifiers::OCL_ExplicitNone:
470    // okay
471    break;
472
473  case Qualifiers::OCL_Weak:
474  case Qualifiers::OCL_Strong:
475  case Qualifiers::OCL_Autoreleasing:
476    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
477      << ValType << FirstArg->getSourceRange();
478    return ExprError();
479  }
480
481  // The majority of builtins return a value, but a few have special return
482  // types, so allow them to override appropriately below.
483  QualType ResultType = ValType;
484
485  // We need to figure out which concrete builtin this maps onto.  For example,
486  // __sync_fetch_and_add with a 2 byte object turns into
487  // __sync_fetch_and_add_2.
488#define BUILTIN_ROW(x) \
489  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
490    Builtin::BI##x##_8, Builtin::BI##x##_16 }
491
492  static const unsigned BuiltinIndices[][5] = {
493    BUILTIN_ROW(__sync_fetch_and_add),
494    BUILTIN_ROW(__sync_fetch_and_sub),
495    BUILTIN_ROW(__sync_fetch_and_or),
496    BUILTIN_ROW(__sync_fetch_and_and),
497    BUILTIN_ROW(__sync_fetch_and_xor),
498
499    BUILTIN_ROW(__sync_add_and_fetch),
500    BUILTIN_ROW(__sync_sub_and_fetch),
501    BUILTIN_ROW(__sync_and_and_fetch),
502    BUILTIN_ROW(__sync_or_and_fetch),
503    BUILTIN_ROW(__sync_xor_and_fetch),
504
505    BUILTIN_ROW(__sync_val_compare_and_swap),
506    BUILTIN_ROW(__sync_bool_compare_and_swap),
507    BUILTIN_ROW(__sync_lock_test_and_set),
508    BUILTIN_ROW(__sync_lock_release),
509    BUILTIN_ROW(__sync_swap)
510  };
511#undef BUILTIN_ROW
512
513  // Determine the index of the size.
514  unsigned SizeIndex;
515  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
516  case 1: SizeIndex = 0; break;
517  case 2: SizeIndex = 1; break;
518  case 4: SizeIndex = 2; break;
519  case 8: SizeIndex = 3; break;
520  case 16: SizeIndex = 4; break;
521  default:
522    Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
523      << FirstArg->getType() << FirstArg->getSourceRange();
524    return ExprError();
525  }
526
527  // Each of these builtins has one pointer argument, followed by some number of
528  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
529  // that we ignore.  Find out which row of BuiltinIndices to read from as well
530  // as the number of fixed args.
531  unsigned BuiltinID = FDecl->getBuiltinID();
532  unsigned BuiltinIndex, NumFixed = 1;
533  switch (BuiltinID) {
534  default: assert(0 && "Unknown overloaded atomic builtin!");
535  case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
536  case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
537  case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
538  case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
539  case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
540
541  case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
542  case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
543  case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
544  case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
545  case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
546
547  case Builtin::BI__sync_val_compare_and_swap:
548    BuiltinIndex = 10;
549    NumFixed = 2;
550    break;
551  case Builtin::BI__sync_bool_compare_and_swap:
552    BuiltinIndex = 11;
553    NumFixed = 2;
554    ResultType = Context.BoolTy;
555    break;
556  case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
557  case Builtin::BI__sync_lock_release:
558    BuiltinIndex = 13;
559    NumFixed = 0;
560    ResultType = Context.VoidTy;
561    break;
562  case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
563  }
564
565  // Now that we know how many fixed arguments we expect, first check that we
566  // have at least that many.
567  if (TheCall->getNumArgs() < 1+NumFixed) {
568    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
569      << 0 << 1+NumFixed << TheCall->getNumArgs()
570      << TheCall->getCallee()->getSourceRange();
571    return ExprError();
572  }
573
574  // Get the decl for the concrete builtin from this, we can tell what the
575  // concrete integer type we should convert to is.
576  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
577  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
578  IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
579  FunctionDecl *NewBuiltinDecl =
580    cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
581                                           TUScope, false, DRE->getLocStart()));
582
583  // The first argument --- the pointer --- has a fixed type; we
584  // deduce the types of the rest of the arguments accordingly.  Walk
585  // the remaining arguments, converting them to the deduced value type.
586  for (unsigned i = 0; i != NumFixed; ++i) {
587    ExprResult Arg = TheCall->getArg(i+1);
588
589    // If the argument is an implicit cast, then there was a promotion due to
590    // "...", just remove it now.
591    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
592      Arg = ICE->getSubExpr();
593      ICE->setSubExpr(0);
594      TheCall->setArg(i+1, Arg.get());
595    }
596
597    // GCC does an implicit conversion to the pointer or integer ValType.  This
598    // can fail in some cases (1i -> int**), check for this error case now.
599    CastKind Kind = CK_Invalid;
600    ExprValueKind VK = VK_RValue;
601    CXXCastPath BasePath;
602    Arg = CheckCastTypes(Arg.get()->getLocStart(), Arg.get()->getSourceRange(),
603                         ValType, Arg.take(), Kind, VK, BasePath);
604    if (Arg.isInvalid())
605      return ExprError();
606
607    // Okay, we have something that *can* be converted to the right type.  Check
608    // to see if there is a potentially weird extension going on here.  This can
609    // happen when you do an atomic operation on something like an char* and
610    // pass in 42.  The 42 gets converted to char.  This is even more strange
611    // for things like 45.123 -> char, etc.
612    // FIXME: Do this check.
613    Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
614    TheCall->setArg(i+1, Arg.get());
615  }
616
617  ASTContext& Context = this->getASTContext();
618
619  // Create a new DeclRefExpr to refer to the new decl.
620  DeclRefExpr* NewDRE = DeclRefExpr::Create(
621      Context,
622      DRE->getQualifierLoc(),
623      NewBuiltinDecl,
624      DRE->getLocation(),
625      NewBuiltinDecl->getType(),
626      DRE->getValueKind());
627
628  // Set the callee in the CallExpr.
629  // FIXME: This leaks the original parens and implicit casts.
630  ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
631  if (PromotedCall.isInvalid())
632    return ExprError();
633  TheCall->setCallee(PromotedCall.take());
634
635  // Change the result type of the call to match the original value type. This
636  // is arbitrary, but the codegen for these builtins ins design to handle it
637  // gracefully.
638  TheCall->setType(ResultType);
639
640  return move(TheCallResult);
641}
642
643
644/// CheckObjCString - Checks that the argument to the builtin
645/// CFString constructor is correct
646/// Note: It might also make sense to do the UTF-16 conversion here (would
647/// simplify the backend).
648bool Sema::CheckObjCString(Expr *Arg) {
649  Arg = Arg->IgnoreParenCasts();
650  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
651
652  if (!Literal || !Literal->isAscii()) {
653    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
654      << Arg->getSourceRange();
655    return true;
656  }
657
658  if (Literal->containsNonAsciiOrNull()) {
659    StringRef String = Literal->getString();
660    unsigned NumBytes = String.size();
661    SmallVector<UTF16, 128> ToBuf(NumBytes);
662    const UTF8 *FromPtr = (UTF8 *)String.data();
663    UTF16 *ToPtr = &ToBuf[0];
664
665    ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
666                                                 &ToPtr, ToPtr + NumBytes,
667                                                 strictConversion);
668    // Check for conversion failure.
669    if (Result != conversionOK)
670      Diag(Arg->getLocStart(),
671           diag::warn_cfstring_truncated) << Arg->getSourceRange();
672  }
673  return false;
674}
675
676/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
677/// Emit an error and return true on failure, return false on success.
678bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
679  Expr *Fn = TheCall->getCallee();
680  if (TheCall->getNumArgs() > 2) {
681    Diag(TheCall->getArg(2)->getLocStart(),
682         diag::err_typecheck_call_too_many_args)
683      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
684      << Fn->getSourceRange()
685      << SourceRange(TheCall->getArg(2)->getLocStart(),
686                     (*(TheCall->arg_end()-1))->getLocEnd());
687    return true;
688  }
689
690  if (TheCall->getNumArgs() < 2) {
691    return Diag(TheCall->getLocEnd(),
692      diag::err_typecheck_call_too_few_args_at_least)
693      << 0 /*function call*/ << 2 << TheCall->getNumArgs();
694  }
695
696  // Type-check the first argument normally.
697  if (checkBuiltinArgument(*this, TheCall, 0))
698    return true;
699
700  // Determine whether the current function is variadic or not.
701  BlockScopeInfo *CurBlock = getCurBlock();
702  bool isVariadic;
703  if (CurBlock)
704    isVariadic = CurBlock->TheDecl->isVariadic();
705  else if (FunctionDecl *FD = getCurFunctionDecl())
706    isVariadic = FD->isVariadic();
707  else
708    isVariadic = getCurMethodDecl()->isVariadic();
709
710  if (!isVariadic) {
711    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
712    return true;
713  }
714
715  // Verify that the second argument to the builtin is the last argument of the
716  // current function or method.
717  bool SecondArgIsLastNamedArgument = false;
718  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
719
720  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
721    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
722      // FIXME: This isn't correct for methods (results in bogus warning).
723      // Get the last formal in the current function.
724      const ParmVarDecl *LastArg;
725      if (CurBlock)
726        LastArg = *(CurBlock->TheDecl->param_end()-1);
727      else if (FunctionDecl *FD = getCurFunctionDecl())
728        LastArg = *(FD->param_end()-1);
729      else
730        LastArg = *(getCurMethodDecl()->param_end()-1);
731      SecondArgIsLastNamedArgument = PV == LastArg;
732    }
733  }
734
735  if (!SecondArgIsLastNamedArgument)
736    Diag(TheCall->getArg(1)->getLocStart(),
737         diag::warn_second_parameter_of_va_start_not_last_named_argument);
738  return false;
739}
740
741/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
742/// friends.  This is declared to take (...), so we have to check everything.
743bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
744  if (TheCall->getNumArgs() < 2)
745    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
746      << 0 << 2 << TheCall->getNumArgs()/*function call*/;
747  if (TheCall->getNumArgs() > 2)
748    return Diag(TheCall->getArg(2)->getLocStart(),
749                diag::err_typecheck_call_too_many_args)
750      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
751      << SourceRange(TheCall->getArg(2)->getLocStart(),
752                     (*(TheCall->arg_end()-1))->getLocEnd());
753
754  ExprResult OrigArg0 = TheCall->getArg(0);
755  ExprResult OrigArg1 = TheCall->getArg(1);
756
757  // Do standard promotions between the two arguments, returning their common
758  // type.
759  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
760  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
761    return true;
762
763  // Make sure any conversions are pushed back into the call; this is
764  // type safe since unordered compare builtins are declared as "_Bool
765  // foo(...)".
766  TheCall->setArg(0, OrigArg0.get());
767  TheCall->setArg(1, OrigArg1.get());
768
769  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
770    return false;
771
772  // If the common type isn't a real floating type, then the arguments were
773  // invalid for this operation.
774  if (!Res->isRealFloatingType())
775    return Diag(OrigArg0.get()->getLocStart(),
776                diag::err_typecheck_call_invalid_ordered_compare)
777      << OrigArg0.get()->getType() << OrigArg1.get()->getType()
778      << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
779
780  return false;
781}
782
783/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
784/// __builtin_isnan and friends.  This is declared to take (...), so we have
785/// to check everything. We expect the last argument to be a floating point
786/// value.
787bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
788  if (TheCall->getNumArgs() < NumArgs)
789    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
790      << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
791  if (TheCall->getNumArgs() > NumArgs)
792    return Diag(TheCall->getArg(NumArgs)->getLocStart(),
793                diag::err_typecheck_call_too_many_args)
794      << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
795      << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
796                     (*(TheCall->arg_end()-1))->getLocEnd());
797
798  Expr *OrigArg = TheCall->getArg(NumArgs-1);
799
800  if (OrigArg->isTypeDependent())
801    return false;
802
803  // This operation requires a non-_Complex floating-point number.
804  if (!OrigArg->getType()->isRealFloatingType())
805    return Diag(OrigArg->getLocStart(),
806                diag::err_typecheck_call_invalid_unary_fp)
807      << OrigArg->getType() << OrigArg->getSourceRange();
808
809  // If this is an implicit conversion from float -> double, remove it.
810  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
811    Expr *CastArg = Cast->getSubExpr();
812    if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
813      assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
814             "promotion from float to double is the only expected cast here");
815      Cast->setSubExpr(0);
816      TheCall->setArg(NumArgs-1, CastArg);
817      OrigArg = CastArg;
818    }
819  }
820
821  return false;
822}
823
824/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
825// This is declared to take (...), so we have to check everything.
826ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
827  if (TheCall->getNumArgs() < 2)
828    return ExprError(Diag(TheCall->getLocEnd(),
829                          diag::err_typecheck_call_too_few_args_at_least)
830      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
831      << TheCall->getSourceRange());
832
833  // Determine which of the following types of shufflevector we're checking:
834  // 1) unary, vector mask: (lhs, mask)
835  // 2) binary, vector mask: (lhs, rhs, mask)
836  // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
837  QualType resType = TheCall->getArg(0)->getType();
838  unsigned numElements = 0;
839
840  if (!TheCall->getArg(0)->isTypeDependent() &&
841      !TheCall->getArg(1)->isTypeDependent()) {
842    QualType LHSType = TheCall->getArg(0)->getType();
843    QualType RHSType = TheCall->getArg(1)->getType();
844
845    if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
846      Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
847        << SourceRange(TheCall->getArg(0)->getLocStart(),
848                       TheCall->getArg(1)->getLocEnd());
849      return ExprError();
850    }
851
852    numElements = LHSType->getAs<VectorType>()->getNumElements();
853    unsigned numResElements = TheCall->getNumArgs() - 2;
854
855    // Check to see if we have a call with 2 vector arguments, the unary shuffle
856    // with mask.  If so, verify that RHS is an integer vector type with the
857    // same number of elts as lhs.
858    if (TheCall->getNumArgs() == 2) {
859      if (!RHSType->hasIntegerRepresentation() ||
860          RHSType->getAs<VectorType>()->getNumElements() != numElements)
861        Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
862          << SourceRange(TheCall->getArg(1)->getLocStart(),
863                         TheCall->getArg(1)->getLocEnd());
864      numResElements = numElements;
865    }
866    else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
867      Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
868        << SourceRange(TheCall->getArg(0)->getLocStart(),
869                       TheCall->getArg(1)->getLocEnd());
870      return ExprError();
871    } else if (numElements != numResElements) {
872      QualType eltType = LHSType->getAs<VectorType>()->getElementType();
873      resType = Context.getVectorType(eltType, numResElements,
874                                      VectorType::GenericVector);
875    }
876  }
877
878  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
879    if (TheCall->getArg(i)->isTypeDependent() ||
880        TheCall->getArg(i)->isValueDependent())
881      continue;
882
883    llvm::APSInt Result(32);
884    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
885      return ExprError(Diag(TheCall->getLocStart(),
886                  diag::err_shufflevector_nonconstant_argument)
887                << TheCall->getArg(i)->getSourceRange());
888
889    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
890      return ExprError(Diag(TheCall->getLocStart(),
891                  diag::err_shufflevector_argument_too_large)
892               << TheCall->getArg(i)->getSourceRange());
893  }
894
895  SmallVector<Expr*, 32> exprs;
896
897  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
898    exprs.push_back(TheCall->getArg(i));
899    TheCall->setArg(i, 0);
900  }
901
902  return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
903                                            exprs.size(), resType,
904                                            TheCall->getCallee()->getLocStart(),
905                                            TheCall->getRParenLoc()));
906}
907
908/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
909// This is declared to take (const void*, ...) and can take two
910// optional constant int args.
911bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
912  unsigned NumArgs = TheCall->getNumArgs();
913
914  if (NumArgs > 3)
915    return Diag(TheCall->getLocEnd(),
916             diag::err_typecheck_call_too_many_args_at_most)
917             << 0 /*function call*/ << 3 << NumArgs
918             << TheCall->getSourceRange();
919
920  // Argument 0 is checked for us and the remaining arguments must be
921  // constant integers.
922  for (unsigned i = 1; i != NumArgs; ++i) {
923    Expr *Arg = TheCall->getArg(i);
924
925    llvm::APSInt Result;
926    if (SemaBuiltinConstantArg(TheCall, i, Result))
927      return true;
928
929    // FIXME: gcc issues a warning and rewrites these to 0. These
930    // seems especially odd for the third argument since the default
931    // is 3.
932    if (i == 1) {
933      if (Result.getLimitedValue() > 1)
934        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
935             << "0" << "1" << Arg->getSourceRange();
936    } else {
937      if (Result.getLimitedValue() > 3)
938        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
939            << "0" << "3" << Arg->getSourceRange();
940    }
941  }
942
943  return false;
944}
945
946/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
947/// TheCall is a constant expression.
948bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
949                                  llvm::APSInt &Result) {
950  Expr *Arg = TheCall->getArg(ArgNum);
951  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
952  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
953
954  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
955
956  if (!Arg->isIntegerConstantExpr(Result, Context))
957    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
958                << FDecl->getDeclName() <<  Arg->getSourceRange();
959
960  return false;
961}
962
963/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
964/// int type). This simply type checks that type is one of the defined
965/// constants (0-3).
966// For compatibility check 0-3, llvm only handles 0 and 2.
967bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
968  llvm::APSInt Result;
969
970  // Check constant-ness first.
971  if (SemaBuiltinConstantArg(TheCall, 1, Result))
972    return true;
973
974  Expr *Arg = TheCall->getArg(1);
975  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
976    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
977             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
978  }
979
980  return false;
981}
982
983/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
984/// This checks that val is a constant 1.
985bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
986  Expr *Arg = TheCall->getArg(1);
987  llvm::APSInt Result;
988
989  // TODO: This is less than ideal. Overload this to take a value.
990  if (SemaBuiltinConstantArg(TheCall, 1, Result))
991    return true;
992
993  if (Result != 1)
994    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
995             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
996
997  return false;
998}
999
1000// Handle i > 1 ? "x" : "y", recursively.
1001bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1002                                  bool HasVAListArg,
1003                                  unsigned format_idx, unsigned firstDataArg,
1004                                  bool isPrintf) {
1005 tryAgain:
1006  if (E->isTypeDependent() || E->isValueDependent())
1007    return false;
1008
1009  E = E->IgnoreParens();
1010
1011  switch (E->getStmtClass()) {
1012  case Stmt::BinaryConditionalOperatorClass:
1013  case Stmt::ConditionalOperatorClass: {
1014    const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
1015    return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1016                                  format_idx, firstDataArg, isPrintf)
1017        && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
1018                                  format_idx, firstDataArg, isPrintf);
1019  }
1020
1021  case Stmt::IntegerLiteralClass:
1022    // Technically -Wformat-nonliteral does not warn about this case.
1023    // The behavior of printf and friends in this case is implementation
1024    // dependent.  Ideally if the format string cannot be null then
1025    // it should have a 'nonnull' attribute in the function prototype.
1026    return true;
1027
1028  case Stmt::ImplicitCastExprClass: {
1029    E = cast<ImplicitCastExpr>(E)->getSubExpr();
1030    goto tryAgain;
1031  }
1032
1033  case Stmt::OpaqueValueExprClass:
1034    if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1035      E = src;
1036      goto tryAgain;
1037    }
1038    return false;
1039
1040  case Stmt::PredefinedExprClass:
1041    // While __func__, etc., are technically not string literals, they
1042    // cannot contain format specifiers and thus are not a security
1043    // liability.
1044    return true;
1045
1046  case Stmt::DeclRefExprClass: {
1047    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1048
1049    // As an exception, do not flag errors for variables binding to
1050    // const string literals.
1051    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1052      bool isConstant = false;
1053      QualType T = DR->getType();
1054
1055      if (const ArrayType *AT = Context.getAsArrayType(T)) {
1056        isConstant = AT->getElementType().isConstant(Context);
1057      } else if (const PointerType *PT = T->getAs<PointerType>()) {
1058        isConstant = T.isConstant(Context) &&
1059                     PT->getPointeeType().isConstant(Context);
1060      }
1061
1062      if (isConstant) {
1063        if (const Expr *Init = VD->getAnyInitializer())
1064          return SemaCheckStringLiteral(Init, TheCall,
1065                                        HasVAListArg, format_idx, firstDataArg,
1066                                        isPrintf);
1067      }
1068
1069      // For vprintf* functions (i.e., HasVAListArg==true), we add a
1070      // special check to see if the format string is a function parameter
1071      // of the function calling the printf function.  If the function
1072      // has an attribute indicating it is a printf-like function, then we
1073      // should suppress warnings concerning non-literals being used in a call
1074      // to a vprintf function.  For example:
1075      //
1076      // void
1077      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1078      //      va_list ap;
1079      //      va_start(ap, fmt);
1080      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1081      //      ...
1082      //
1083      //
1084      //  FIXME: We don't have full attribute support yet, so just check to see
1085      //    if the argument is a DeclRefExpr that references a parameter.  We'll
1086      //    add proper support for checking the attribute later.
1087      if (HasVAListArg)
1088        if (isa<ParmVarDecl>(VD))
1089          return true;
1090    }
1091
1092    return false;
1093  }
1094
1095  case Stmt::CallExprClass: {
1096    const CallExpr *CE = cast<CallExpr>(E);
1097    if (const ImplicitCastExpr *ICE
1098          = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1099      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1100        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1101          if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
1102            unsigned ArgIndex = FA->getFormatIdx();
1103            const Expr *Arg = CE->getArg(ArgIndex - 1);
1104
1105            return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
1106                                          format_idx, firstDataArg, isPrintf);
1107          }
1108        }
1109      }
1110    }
1111
1112    return false;
1113  }
1114  case Stmt::ObjCStringLiteralClass:
1115  case Stmt::StringLiteralClass: {
1116    const StringLiteral *StrE = NULL;
1117
1118    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1119      StrE = ObjCFExpr->getString();
1120    else
1121      StrE = cast<StringLiteral>(E);
1122
1123    if (StrE) {
1124      CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1125                        firstDataArg, isPrintf);
1126      return true;
1127    }
1128
1129    return false;
1130  }
1131
1132  default:
1133    return false;
1134  }
1135}
1136
1137void
1138Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1139                            const Expr * const *ExprArgs,
1140                            SourceLocation CallSiteLoc) {
1141  for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1142                                  e = NonNull->args_end();
1143       i != e; ++i) {
1144    const Expr *ArgExpr = ExprArgs[*i];
1145    if (ArgExpr->isNullPointerConstant(Context,
1146                                       Expr::NPC_ValueDependentIsNotNull))
1147      Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1148  }
1149}
1150
1151/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1152/// functions) for correct use of format strings.
1153void
1154Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1155                                unsigned format_idx, unsigned firstDataArg,
1156                                bool isPrintf) {
1157
1158  const Expr *Fn = TheCall->getCallee();
1159
1160  // The way the format attribute works in GCC, the implicit this argument
1161  // of member functions is counted. However, it doesn't appear in our own
1162  // lists, so decrement format_idx in that case.
1163  if (isa<CXXMemberCallExpr>(TheCall)) {
1164    const CXXMethodDecl *method_decl =
1165      dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1166    if (method_decl && method_decl->isInstance()) {
1167      // Catch a format attribute mistakenly referring to the object argument.
1168      if (format_idx == 0)
1169        return;
1170      --format_idx;
1171      if(firstDataArg != 0)
1172        --firstDataArg;
1173    }
1174  }
1175
1176  // CHECK: printf/scanf-like function is called with no format string.
1177  if (format_idx >= TheCall->getNumArgs()) {
1178    Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
1179      << Fn->getSourceRange();
1180    return;
1181  }
1182
1183  const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
1184
1185  // CHECK: format string is not a string literal.
1186  //
1187  // Dynamically generated format strings are difficult to
1188  // automatically vet at compile time.  Requiring that format strings
1189  // are string literals: (1) permits the checking of format strings by
1190  // the compiler and thereby (2) can practically remove the source of
1191  // many format string exploits.
1192
1193  // Format string can be either ObjC string (e.g. @"%d") or
1194  // C string (e.g. "%d")
1195  // ObjC string uses the same format specifiers as C string, so we can use
1196  // the same format string checking logic for both ObjC and C strings.
1197  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1198                             firstDataArg, isPrintf))
1199    return;  // Literal format string found, check done!
1200
1201  // If there are no arguments specified, warn with -Wformat-security, otherwise
1202  // warn only with -Wformat-nonliteral.
1203  if (TheCall->getNumArgs() == format_idx+1)
1204    Diag(TheCall->getArg(format_idx)->getLocStart(),
1205         diag::warn_format_nonliteral_noargs)
1206      << OrigFormatExpr->getSourceRange();
1207  else
1208    Diag(TheCall->getArg(format_idx)->getLocStart(),
1209         diag::warn_format_nonliteral)
1210           << OrigFormatExpr->getSourceRange();
1211}
1212
1213namespace {
1214class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1215protected:
1216  Sema &S;
1217  const StringLiteral *FExpr;
1218  const Expr *OrigFormatExpr;
1219  const unsigned FirstDataArg;
1220  const unsigned NumDataArgs;
1221  const bool IsObjCLiteral;
1222  const char *Beg; // Start of format string.
1223  const bool HasVAListArg;
1224  const CallExpr *TheCall;
1225  unsigned FormatIdx;
1226  llvm::BitVector CoveredArgs;
1227  bool usesPositionalArgs;
1228  bool atFirstArg;
1229public:
1230  CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1231                     const Expr *origFormatExpr, unsigned firstDataArg,
1232                     unsigned numDataArgs, bool isObjCLiteral,
1233                     const char *beg, bool hasVAListArg,
1234                     const CallExpr *theCall, unsigned formatIdx)
1235    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1236      FirstDataArg(firstDataArg),
1237      NumDataArgs(numDataArgs),
1238      IsObjCLiteral(isObjCLiteral), Beg(beg),
1239      HasVAListArg(hasVAListArg),
1240      TheCall(theCall), FormatIdx(formatIdx),
1241      usesPositionalArgs(false), atFirstArg(true) {
1242        CoveredArgs.resize(numDataArgs);
1243        CoveredArgs.reset();
1244      }
1245
1246  void DoneProcessing();
1247
1248  void HandleIncompleteSpecifier(const char *startSpecifier,
1249                                 unsigned specifierLen);
1250
1251  virtual void HandleInvalidPosition(const char *startSpecifier,
1252                                     unsigned specifierLen,
1253                                     analyze_format_string::PositionContext p);
1254
1255  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1256
1257  void HandleNullChar(const char *nullCharacter);
1258
1259protected:
1260  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1261                                        const char *startSpec,
1262                                        unsigned specifierLen,
1263                                        const char *csStart, unsigned csLen);
1264
1265  SourceRange getFormatStringRange();
1266  CharSourceRange getSpecifierRange(const char *startSpecifier,
1267                                    unsigned specifierLen);
1268  SourceLocation getLocationOfByte(const char *x);
1269
1270  const Expr *getDataArg(unsigned i) const;
1271
1272  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1273                    const analyze_format_string::ConversionSpecifier &CS,
1274                    const char *startSpecifier, unsigned specifierLen,
1275                    unsigned argIndex);
1276};
1277}
1278
1279SourceRange CheckFormatHandler::getFormatStringRange() {
1280  return OrigFormatExpr->getSourceRange();
1281}
1282
1283CharSourceRange CheckFormatHandler::
1284getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1285  SourceLocation Start = getLocationOfByte(startSpecifier);
1286  SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1287
1288  // Advance the end SourceLocation by one due to half-open ranges.
1289  End = End.getFileLocWithOffset(1);
1290
1291  return CharSourceRange::getCharRange(Start, End);
1292}
1293
1294SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1295  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1296}
1297
1298void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1299                                                   unsigned specifierLen){
1300  SourceLocation Loc = getLocationOfByte(startSpecifier);
1301  S.Diag(Loc, diag::warn_printf_incomplete_specifier)
1302    << getSpecifierRange(startSpecifier, specifierLen);
1303}
1304
1305void
1306CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1307                                     analyze_format_string::PositionContext p) {
1308  SourceLocation Loc = getLocationOfByte(startPos);
1309  S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1310    << (unsigned) p << getSpecifierRange(startPos, posLen);
1311}
1312
1313void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1314                                            unsigned posLen) {
1315  SourceLocation Loc = getLocationOfByte(startPos);
1316  S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1317    << getSpecifierRange(startPos, posLen);
1318}
1319
1320void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1321  if (!IsObjCLiteral) {
1322    // The presence of a null character is likely an error.
1323    S.Diag(getLocationOfByte(nullCharacter),
1324           diag::warn_printf_format_string_contains_null_char)
1325      << getFormatStringRange();
1326  }
1327}
1328
1329const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1330  return TheCall->getArg(FirstDataArg + i);
1331}
1332
1333void CheckFormatHandler::DoneProcessing() {
1334    // Does the number of data arguments exceed the number of
1335    // format conversions in the format string?
1336  if (!HasVAListArg) {
1337      // Find any arguments that weren't covered.
1338    CoveredArgs.flip();
1339    signed notCoveredArg = CoveredArgs.find_first();
1340    if (notCoveredArg >= 0) {
1341      assert((unsigned)notCoveredArg < NumDataArgs);
1342      S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1343             diag::warn_printf_data_arg_not_used)
1344      << getFormatStringRange();
1345    }
1346  }
1347}
1348
1349bool
1350CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1351                                                     SourceLocation Loc,
1352                                                     const char *startSpec,
1353                                                     unsigned specifierLen,
1354                                                     const char *csStart,
1355                                                     unsigned csLen) {
1356
1357  bool keepGoing = true;
1358  if (argIndex < NumDataArgs) {
1359    // Consider the argument coverered, even though the specifier doesn't
1360    // make sense.
1361    CoveredArgs.set(argIndex);
1362  }
1363  else {
1364    // If argIndex exceeds the number of data arguments we
1365    // don't issue a warning because that is just a cascade of warnings (and
1366    // they may have intended '%%' anyway). We don't want to continue processing
1367    // the format string after this point, however, as we will like just get
1368    // gibberish when trying to match arguments.
1369    keepGoing = false;
1370  }
1371
1372  S.Diag(Loc, diag::warn_format_invalid_conversion)
1373    << StringRef(csStart, csLen)
1374    << getSpecifierRange(startSpec, specifierLen);
1375
1376  return keepGoing;
1377}
1378
1379bool
1380CheckFormatHandler::CheckNumArgs(
1381  const analyze_format_string::FormatSpecifier &FS,
1382  const analyze_format_string::ConversionSpecifier &CS,
1383  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1384
1385  if (argIndex >= NumDataArgs) {
1386    if (FS.usesPositionalArg())  {
1387      S.Diag(getLocationOfByte(CS.getStart()),
1388             diag::warn_printf_positional_arg_exceeds_data_args)
1389      << (argIndex+1) << NumDataArgs
1390      << getSpecifierRange(startSpecifier, specifierLen);
1391    }
1392    else {
1393      S.Diag(getLocationOfByte(CS.getStart()),
1394             diag::warn_printf_insufficient_data_args)
1395      << getSpecifierRange(startSpecifier, specifierLen);
1396    }
1397
1398    return false;
1399  }
1400  return true;
1401}
1402
1403//===--- CHECK: Printf format string checking ------------------------------===//
1404
1405namespace {
1406class CheckPrintfHandler : public CheckFormatHandler {
1407public:
1408  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1409                     const Expr *origFormatExpr, unsigned firstDataArg,
1410                     unsigned numDataArgs, bool isObjCLiteral,
1411                     const char *beg, bool hasVAListArg,
1412                     const CallExpr *theCall, unsigned formatIdx)
1413  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1414                       numDataArgs, isObjCLiteral, beg, hasVAListArg,
1415                       theCall, formatIdx) {}
1416
1417
1418  bool HandleInvalidPrintfConversionSpecifier(
1419                                      const analyze_printf::PrintfSpecifier &FS,
1420                                      const char *startSpecifier,
1421                                      unsigned specifierLen);
1422
1423  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1424                             const char *startSpecifier,
1425                             unsigned specifierLen);
1426
1427  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1428                    const char *startSpecifier, unsigned specifierLen);
1429  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1430                           const analyze_printf::OptionalAmount &Amt,
1431                           unsigned type,
1432                           const char *startSpecifier, unsigned specifierLen);
1433  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1434                  const analyze_printf::OptionalFlag &flag,
1435                  const char *startSpecifier, unsigned specifierLen);
1436  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1437                         const analyze_printf::OptionalFlag &ignoredFlag,
1438                         const analyze_printf::OptionalFlag &flag,
1439                         const char *startSpecifier, unsigned specifierLen);
1440};
1441}
1442
1443bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1444                                      const analyze_printf::PrintfSpecifier &FS,
1445                                      const char *startSpecifier,
1446                                      unsigned specifierLen) {
1447  const analyze_printf::PrintfConversionSpecifier &CS =
1448    FS.getConversionSpecifier();
1449
1450  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1451                                          getLocationOfByte(CS.getStart()),
1452                                          startSpecifier, specifierLen,
1453                                          CS.getStart(), CS.getLength());
1454}
1455
1456bool CheckPrintfHandler::HandleAmount(
1457                               const analyze_format_string::OptionalAmount &Amt,
1458                               unsigned k, const char *startSpecifier,
1459                               unsigned specifierLen) {
1460
1461  if (Amt.hasDataArgument()) {
1462    if (!HasVAListArg) {
1463      unsigned argIndex = Amt.getArgIndex();
1464      if (argIndex >= NumDataArgs) {
1465        S.Diag(getLocationOfByte(Amt.getStart()),
1466               diag::warn_printf_asterisk_missing_arg)
1467          << k << getSpecifierRange(startSpecifier, specifierLen);
1468        // Don't do any more checking.  We will just emit
1469        // spurious errors.
1470        return false;
1471      }
1472
1473      // Type check the data argument.  It should be an 'int'.
1474      // Although not in conformance with C99, we also allow the argument to be
1475      // an 'unsigned int' as that is a reasonably safe case.  GCC also
1476      // doesn't emit a warning for that case.
1477      CoveredArgs.set(argIndex);
1478      const Expr *Arg = getDataArg(argIndex);
1479      QualType T = Arg->getType();
1480
1481      const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1482      assert(ATR.isValid());
1483
1484      if (!ATR.matchesType(S.Context, T)) {
1485        S.Diag(getLocationOfByte(Amt.getStart()),
1486               diag::warn_printf_asterisk_wrong_type)
1487          << k
1488          << ATR.getRepresentativeType(S.Context) << T
1489          << getSpecifierRange(startSpecifier, specifierLen)
1490          << Arg->getSourceRange();
1491        // Don't do any more checking.  We will just emit
1492        // spurious errors.
1493        return false;
1494      }
1495    }
1496  }
1497  return true;
1498}
1499
1500void CheckPrintfHandler::HandleInvalidAmount(
1501                                      const analyze_printf::PrintfSpecifier &FS,
1502                                      const analyze_printf::OptionalAmount &Amt,
1503                                      unsigned type,
1504                                      const char *startSpecifier,
1505                                      unsigned specifierLen) {
1506  const analyze_printf::PrintfConversionSpecifier &CS =
1507    FS.getConversionSpecifier();
1508  switch (Amt.getHowSpecified()) {
1509  case analyze_printf::OptionalAmount::Constant:
1510    S.Diag(getLocationOfByte(Amt.getStart()),
1511        diag::warn_printf_nonsensical_optional_amount)
1512      << type
1513      << CS.toString()
1514      << getSpecifierRange(startSpecifier, specifierLen)
1515      << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1516          Amt.getConstantLength()));
1517    break;
1518
1519  default:
1520    S.Diag(getLocationOfByte(Amt.getStart()),
1521        diag::warn_printf_nonsensical_optional_amount)
1522      << type
1523      << CS.toString()
1524      << getSpecifierRange(startSpecifier, specifierLen);
1525    break;
1526  }
1527}
1528
1529void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1530                                    const analyze_printf::OptionalFlag &flag,
1531                                    const char *startSpecifier,
1532                                    unsigned specifierLen) {
1533  // Warn about pointless flag with a fixit removal.
1534  const analyze_printf::PrintfConversionSpecifier &CS =
1535    FS.getConversionSpecifier();
1536  S.Diag(getLocationOfByte(flag.getPosition()),
1537      diag::warn_printf_nonsensical_flag)
1538    << flag.toString() << CS.toString()
1539    << getSpecifierRange(startSpecifier, specifierLen)
1540    << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
1541}
1542
1543void CheckPrintfHandler::HandleIgnoredFlag(
1544                                const analyze_printf::PrintfSpecifier &FS,
1545                                const analyze_printf::OptionalFlag &ignoredFlag,
1546                                const analyze_printf::OptionalFlag &flag,
1547                                const char *startSpecifier,
1548                                unsigned specifierLen) {
1549  // Warn about ignored flag with a fixit removal.
1550  S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1551      diag::warn_printf_ignored_flag)
1552    << ignoredFlag.toString() << flag.toString()
1553    << getSpecifierRange(startSpecifier, specifierLen)
1554    << FixItHint::CreateRemoval(getSpecifierRange(
1555        ignoredFlag.getPosition(), 1));
1556}
1557
1558bool
1559CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
1560                                            &FS,
1561                                          const char *startSpecifier,
1562                                          unsigned specifierLen) {
1563
1564  using namespace analyze_format_string;
1565  using namespace analyze_printf;
1566  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
1567
1568  if (FS.consumesDataArgument()) {
1569    if (atFirstArg) {
1570        atFirstArg = false;
1571        usesPositionalArgs = FS.usesPositionalArg();
1572    }
1573    else if (usesPositionalArgs != FS.usesPositionalArg()) {
1574      // Cannot mix-and-match positional and non-positional arguments.
1575      S.Diag(getLocationOfByte(CS.getStart()),
1576             diag::warn_format_mix_positional_nonpositional_args)
1577        << getSpecifierRange(startSpecifier, specifierLen);
1578      return false;
1579    }
1580  }
1581
1582  // First check if the field width, precision, and conversion specifier
1583  // have matching data arguments.
1584  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1585                    startSpecifier, specifierLen)) {
1586    return false;
1587  }
1588
1589  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1590                    startSpecifier, specifierLen)) {
1591    return false;
1592  }
1593
1594  if (!CS.consumesDataArgument()) {
1595    // FIXME: Technically specifying a precision or field width here
1596    // makes no sense.  Worth issuing a warning at some point.
1597    return true;
1598  }
1599
1600  // Consume the argument.
1601  unsigned argIndex = FS.getArgIndex();
1602  if (argIndex < NumDataArgs) {
1603    // The check to see if the argIndex is valid will come later.
1604    // We set the bit here because we may exit early from this
1605    // function if we encounter some other error.
1606    CoveredArgs.set(argIndex);
1607  }
1608
1609  // Check for using an Objective-C specific conversion specifier
1610  // in a non-ObjC literal.
1611  if (!IsObjCLiteral && CS.isObjCArg()) {
1612    return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1613                                                  specifierLen);
1614  }
1615
1616  // Check for invalid use of field width
1617  if (!FS.hasValidFieldWidth()) {
1618    HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
1619        startSpecifier, specifierLen);
1620  }
1621
1622  // Check for invalid use of precision
1623  if (!FS.hasValidPrecision()) {
1624    HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1625        startSpecifier, specifierLen);
1626  }
1627
1628  // Check each flag does not conflict with any other component.
1629  if (!FS.hasValidThousandsGroupingPrefix())
1630    HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
1631  if (!FS.hasValidLeadingZeros())
1632    HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1633  if (!FS.hasValidPlusPrefix())
1634    HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
1635  if (!FS.hasValidSpacePrefix())
1636    HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
1637  if (!FS.hasValidAlternativeForm())
1638    HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1639  if (!FS.hasValidLeftJustified())
1640    HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1641
1642  // Check that flags are not ignored by another flag
1643  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1644    HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1645        startSpecifier, specifierLen);
1646  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1647    HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1648            startSpecifier, specifierLen);
1649
1650  // Check the length modifier is valid with the given conversion specifier.
1651  const LengthModifier &LM = FS.getLengthModifier();
1652  if (!FS.hasValidLengthModifier())
1653    S.Diag(getLocationOfByte(LM.getStart()),
1654        diag::warn_format_nonsensical_length)
1655      << LM.toString() << CS.toString()
1656      << getSpecifierRange(startSpecifier, specifierLen)
1657      << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1658          LM.getLength()));
1659
1660  // Are we using '%n'?
1661  if (CS.getKind() == ConversionSpecifier::nArg) {
1662    // Issue a warning about this being a possible security issue.
1663    S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
1664      << getSpecifierRange(startSpecifier, specifierLen);
1665    // Continue checking the other format specifiers.
1666    return true;
1667  }
1668
1669  // The remaining checks depend on the data arguments.
1670  if (HasVAListArg)
1671    return true;
1672
1673  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
1674    return false;
1675
1676  // Now type check the data expression that matches the
1677  // format specifier.
1678  const Expr *Ex = getDataArg(argIndex);
1679  const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1680  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1681    // Check if we didn't match because of an implicit cast from a 'char'
1682    // or 'short' to an 'int'.  This is done because printf is a varargs
1683    // function.
1684    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1685      if (ICE->getType() == S.Context.IntTy) {
1686        // All further checking is done on the subexpression.
1687        Ex = ICE->getSubExpr();
1688        if (ATR.matchesType(S.Context, Ex->getType()))
1689          return true;
1690      }
1691
1692    // We may be able to offer a FixItHint if it is a supported type.
1693    PrintfSpecifier fixedFS = FS;
1694    bool success = fixedFS.fixType(Ex->getType());
1695
1696    if (success) {
1697      // Get the fix string from the fixed format specifier
1698      llvm::SmallString<128> buf;
1699      llvm::raw_svector_ostream os(buf);
1700      fixedFS.toString(os);
1701
1702      // FIXME: getRepresentativeType() perhaps should return a string
1703      // instead of a QualType to better handle when the representative
1704      // type is 'wint_t' (which is defined in the system headers).
1705      S.Diag(getLocationOfByte(CS.getStart()),
1706          diag::warn_printf_conversion_argument_type_mismatch)
1707        << ATR.getRepresentativeType(S.Context) << Ex->getType()
1708        << getSpecifierRange(startSpecifier, specifierLen)
1709        << Ex->getSourceRange()
1710        << FixItHint::CreateReplacement(
1711            getSpecifierRange(startSpecifier, specifierLen),
1712            os.str());
1713    }
1714    else {
1715      S.Diag(getLocationOfByte(CS.getStart()),
1716             diag::warn_printf_conversion_argument_type_mismatch)
1717        << ATR.getRepresentativeType(S.Context) << Ex->getType()
1718        << getSpecifierRange(startSpecifier, specifierLen)
1719        << Ex->getSourceRange();
1720    }
1721  }
1722
1723  return true;
1724}
1725
1726//===--- CHECK: Scanf format string checking ------------------------------===//
1727
1728namespace {
1729class CheckScanfHandler : public CheckFormatHandler {
1730public:
1731  CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1732                    const Expr *origFormatExpr, unsigned firstDataArg,
1733                    unsigned numDataArgs, bool isObjCLiteral,
1734                    const char *beg, bool hasVAListArg,
1735                    const CallExpr *theCall, unsigned formatIdx)
1736  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1737                       numDataArgs, isObjCLiteral, beg, hasVAListArg,
1738                       theCall, formatIdx) {}
1739
1740  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1741                            const char *startSpecifier,
1742                            unsigned specifierLen);
1743
1744  bool HandleInvalidScanfConversionSpecifier(
1745          const analyze_scanf::ScanfSpecifier &FS,
1746          const char *startSpecifier,
1747          unsigned specifierLen);
1748
1749  void HandleIncompleteScanList(const char *start, const char *end);
1750};
1751}
1752
1753void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1754                                                 const char *end) {
1755  S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1756    << getSpecifierRange(start, end - start);
1757}
1758
1759bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1760                                        const analyze_scanf::ScanfSpecifier &FS,
1761                                        const char *startSpecifier,
1762                                        unsigned specifierLen) {
1763
1764  const analyze_scanf::ScanfConversionSpecifier &CS =
1765    FS.getConversionSpecifier();
1766
1767  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1768                                          getLocationOfByte(CS.getStart()),
1769                                          startSpecifier, specifierLen,
1770                                          CS.getStart(), CS.getLength());
1771}
1772
1773bool CheckScanfHandler::HandleScanfSpecifier(
1774                                       const analyze_scanf::ScanfSpecifier &FS,
1775                                       const char *startSpecifier,
1776                                       unsigned specifierLen) {
1777
1778  using namespace analyze_scanf;
1779  using namespace analyze_format_string;
1780
1781  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
1782
1783  // Handle case where '%' and '*' don't consume an argument.  These shouldn't
1784  // be used to decide if we are using positional arguments consistently.
1785  if (FS.consumesDataArgument()) {
1786    if (atFirstArg) {
1787      atFirstArg = false;
1788      usesPositionalArgs = FS.usesPositionalArg();
1789    }
1790    else if (usesPositionalArgs != FS.usesPositionalArg()) {
1791      // Cannot mix-and-match positional and non-positional arguments.
1792      S.Diag(getLocationOfByte(CS.getStart()),
1793             diag::warn_format_mix_positional_nonpositional_args)
1794        << getSpecifierRange(startSpecifier, specifierLen);
1795      return false;
1796    }
1797  }
1798
1799  // Check if the field with is non-zero.
1800  const OptionalAmount &Amt = FS.getFieldWidth();
1801  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1802    if (Amt.getConstantAmount() == 0) {
1803      const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1804                                                   Amt.getConstantLength());
1805      S.Diag(getLocationOfByte(Amt.getStart()),
1806             diag::warn_scanf_nonzero_width)
1807        << R << FixItHint::CreateRemoval(R);
1808    }
1809  }
1810
1811  if (!FS.consumesDataArgument()) {
1812    // FIXME: Technically specifying a precision or field width here
1813    // makes no sense.  Worth issuing a warning at some point.
1814    return true;
1815  }
1816
1817  // Consume the argument.
1818  unsigned argIndex = FS.getArgIndex();
1819  if (argIndex < NumDataArgs) {
1820      // The check to see if the argIndex is valid will come later.
1821      // We set the bit here because we may exit early from this
1822      // function if we encounter some other error.
1823    CoveredArgs.set(argIndex);
1824  }
1825
1826  // Check the length modifier is valid with the given conversion specifier.
1827  const LengthModifier &LM = FS.getLengthModifier();
1828  if (!FS.hasValidLengthModifier()) {
1829    S.Diag(getLocationOfByte(LM.getStart()),
1830           diag::warn_format_nonsensical_length)
1831      << LM.toString() << CS.toString()
1832      << getSpecifierRange(startSpecifier, specifierLen)
1833      << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1834                                                    LM.getLength()));
1835  }
1836
1837  // The remaining checks depend on the data arguments.
1838  if (HasVAListArg)
1839    return true;
1840
1841  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
1842    return false;
1843
1844  // FIXME: Check that the argument type matches the format specifier.
1845
1846  return true;
1847}
1848
1849void Sema::CheckFormatString(const StringLiteral *FExpr,
1850                             const Expr *OrigFormatExpr,
1851                             const CallExpr *TheCall, bool HasVAListArg,
1852                             unsigned format_idx, unsigned firstDataArg,
1853                             bool isPrintf) {
1854
1855  // CHECK: is the format string a wide literal?
1856  if (!FExpr->isAscii()) {
1857    Diag(FExpr->getLocStart(),
1858         diag::warn_format_string_is_wide_literal)
1859    << OrigFormatExpr->getSourceRange();
1860    return;
1861  }
1862
1863  // Str - The format string.  NOTE: this is NOT null-terminated!
1864  StringRef StrRef = FExpr->getString();
1865  const char *Str = StrRef.data();
1866  unsigned StrLen = StrRef.size();
1867
1868  // CHECK: empty format string?
1869  if (StrLen == 0) {
1870    Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
1871    << OrigFormatExpr->getSourceRange();
1872    return;
1873  }
1874
1875  if (isPrintf) {
1876    CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1877                         TheCall->getNumArgs() - firstDataArg,
1878                         isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1879                         HasVAListArg, TheCall, format_idx);
1880
1881    if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1882      H.DoneProcessing();
1883  }
1884  else {
1885    CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1886                        TheCall->getNumArgs() - firstDataArg,
1887                        isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1888                        HasVAListArg, TheCall, format_idx);
1889
1890    if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1891      H.DoneProcessing();
1892  }
1893}
1894
1895//===--- CHECK: Standard memory functions ---------------------------------===//
1896
1897/// \brief Determine whether the given type is a dynamic class type (e.g.,
1898/// whether it has a vtable).
1899static bool isDynamicClassType(QualType T) {
1900  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
1901    if (CXXRecordDecl *Definition = Record->getDefinition())
1902      if (Definition->isDynamicClass())
1903        return true;
1904
1905  return false;
1906}
1907
1908/// \brief If E is a sizeof expression, returns its argument expression,
1909/// otherwise returns NULL.
1910static const Expr *getSizeOfExprArg(const Expr* E) {
1911  if (const UnaryExprOrTypeTraitExpr *SizeOf =
1912      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1913    if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
1914      return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
1915
1916  return 0;
1917}
1918
1919/// \brief If E is a sizeof expression, returns its argument type.
1920static QualType getSizeOfArgType(const Expr* E) {
1921  if (const UnaryExprOrTypeTraitExpr *SizeOf =
1922      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1923    if (SizeOf->getKind() == clang::UETT_SizeOf)
1924      return SizeOf->getTypeOfArgument();
1925
1926  return QualType();
1927}
1928
1929/// \brief Check for dangerous or invalid arguments to memset().
1930///
1931/// This issues warnings on known problematic, dangerous or unspecified
1932/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
1933/// function calls.
1934///
1935/// \param Call The call expression to diagnose.
1936void Sema::CheckMemaccessArguments(const CallExpr *Call,
1937                                   CheckedMemoryFunction CMF,
1938                                   IdentifierInfo *FnName) {
1939  // It is possible to have a non-standard definition of memset.  Validate
1940  // we have enough arguments, and if not, abort further checking.
1941  if (Call->getNumArgs() < 3)
1942    return;
1943
1944  unsigned LastArg = (CMF == CMF_Memset? 1 : 2);
1945  const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts();
1946
1947  // We have special checking when the length is a sizeof expression.
1948  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
1949  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
1950  llvm::FoldingSetNodeID SizeOfArgID;
1951
1952  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
1953    const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
1954    SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
1955
1956    QualType DestTy = Dest->getType();
1957    if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1958      QualType PointeeTy = DestPtrTy->getPointeeType();
1959
1960      // Never warn about void type pointers. This can be used to suppress
1961      // false positives.
1962      if (PointeeTy->isVoidType())
1963        continue;
1964
1965      // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
1966      // actually comparing the expressions for equality. Because computing the
1967      // expression IDs can be expensive, we only do this if the diagnostic is
1968      // enabled.
1969      if (SizeOfArg &&
1970          Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
1971                                   SizeOfArg->getExprLoc())) {
1972        // We only compute IDs for expressions if the warning is enabled, and
1973        // cache the sizeof arg's ID.
1974        if (SizeOfArgID == llvm::FoldingSetNodeID())
1975          SizeOfArg->Profile(SizeOfArgID, Context, true);
1976        llvm::FoldingSetNodeID DestID;
1977        Dest->Profile(DestID, Context, true);
1978        if (DestID == SizeOfArgID) {
1979          unsigned ActionIdx = 0; // Default is to suggest dereferencing.
1980          if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
1981            if (UnaryOp->getOpcode() == UO_AddrOf)
1982              ActionIdx = 1; // If its an address-of operator, just remove it.
1983          if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
1984            ActionIdx = 2; // If the pointee's size is sizeof(char),
1985                           // suggest an explicit length.
1986          DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
1987                              PDiag(diag::warn_sizeof_pointer_expr_memaccess)
1988                                << FnName << ArgIdx << ActionIdx
1989                                << Dest->getSourceRange()
1990                                << SizeOfArg->getSourceRange());
1991          break;
1992        }
1993      }
1994
1995      // Also check for cases where the sizeof argument is the exact same
1996      // type as the memory argument, and where it points to a user-defined
1997      // record type.
1998      if (SizeOfArgTy != QualType()) {
1999        if (PointeeTy->isRecordType() &&
2000            Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2001          DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2002                              PDiag(diag::warn_sizeof_pointer_type_memaccess)
2003                                << FnName << SizeOfArgTy << ArgIdx
2004                                << PointeeTy << Dest->getSourceRange()
2005                                << LenExpr->getSourceRange());
2006          break;
2007        }
2008      }
2009
2010      // Always complain about dynamic classes.
2011      if (isDynamicClassType(PointeeTy))
2012        DiagRuntimeBehavior(
2013          Dest->getExprLoc(), Dest,
2014          PDiag(diag::warn_dyn_class_memaccess)
2015            << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2016            // "overwritten" if we're warning about the destination for any call
2017            // but memcmp; otherwise a verb appropriate to the call.
2018            << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2019            << Call->getCallee()->getSourceRange());
2020      else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
2021        DiagRuntimeBehavior(
2022          Dest->getExprLoc(), Dest,
2023          PDiag(diag::warn_arc_object_memaccess)
2024            << ArgIdx << FnName << PointeeTy
2025            << Call->getCallee()->getSourceRange());
2026      else
2027        continue;
2028
2029      DiagRuntimeBehavior(
2030        Dest->getExprLoc(), Dest,
2031        PDiag(diag::note_bad_memaccess_silence)
2032          << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2033      break;
2034    }
2035  }
2036}
2037
2038// A little helper routine: ignore addition and subtraction of integer literals.
2039// This intentionally does not ignore all integer constant expressions because
2040// we don't want to remove sizeof().
2041static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2042  Ex = Ex->IgnoreParenCasts();
2043
2044  for (;;) {
2045    const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2046    if (!BO || !BO->isAdditiveOp())
2047      break;
2048
2049    const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2050    const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2051
2052    if (isa<IntegerLiteral>(RHS))
2053      Ex = LHS;
2054    else if (isa<IntegerLiteral>(LHS))
2055      Ex = RHS;
2056    else
2057      break;
2058  }
2059
2060  return Ex;
2061}
2062
2063// Warn if the user has made the 'size' argument to strlcpy or strlcat
2064// be the size of the source, instead of the destination.
2065void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2066                                    IdentifierInfo *FnName) {
2067
2068  // Don't crash if the user has the wrong number of arguments
2069  if (Call->getNumArgs() != 3)
2070    return;
2071
2072  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2073  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2074  const Expr *CompareWithSrc = NULL;
2075
2076  // Look for 'strlcpy(dst, x, sizeof(x))'
2077  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2078    CompareWithSrc = Ex;
2079  else {
2080    // Look for 'strlcpy(dst, x, strlen(x))'
2081    if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2082      if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2083          && SizeCall->getNumArgs() == 1)
2084        CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2085    }
2086  }
2087
2088  if (!CompareWithSrc)
2089    return;
2090
2091  // Determine if the argument to sizeof/strlen is equal to the source
2092  // argument.  In principle there's all kinds of things you could do
2093  // here, for instance creating an == expression and evaluating it with
2094  // EvaluateAsBooleanCondition, but this uses a more direct technique:
2095  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2096  if (!SrcArgDRE)
2097    return;
2098
2099  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2100  if (!CompareWithSrcDRE ||
2101      SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2102    return;
2103
2104  const Expr *OriginalSizeArg = Call->getArg(2);
2105  Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2106    << OriginalSizeArg->getSourceRange() << FnName;
2107
2108  // Output a FIXIT hint if the destination is an array (rather than a
2109  // pointer to an array).  This could be enhanced to handle some
2110  // pointers if we know the actual size, like if DstArg is 'array+2'
2111  // we could say 'sizeof(array)-2'.
2112  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
2113  QualType DstArgTy = DstArg->getType();
2114
2115  // Only handle constant-sized or VLAs, but not flexible members.
2116  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2117    // Only issue the FIXIT for arrays of size > 1.
2118    if (CAT->getSize().getSExtValue() <= 1)
2119      return;
2120  } else if (!DstArgTy->isVariableArrayType()) {
2121    return;
2122  }
2123
2124  llvm::SmallString<128> sizeString;
2125  llvm::raw_svector_ostream OS(sizeString);
2126  OS << "sizeof(";
2127  DstArg->printPretty(OS, Context, 0, Context.PrintingPolicy);
2128  OS << ")";
2129
2130  Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2131    << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2132                                    OS.str());
2133}
2134
2135//===--- CHECK: Return Address of Stack Variable --------------------------===//
2136
2137static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2138static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
2139
2140/// CheckReturnStackAddr - Check if a return statement returns the address
2141///   of a stack variable.
2142void
2143Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2144                           SourceLocation ReturnLoc) {
2145
2146  Expr *stackE = 0;
2147  SmallVector<DeclRefExpr *, 8> refVars;
2148
2149  // Perform checking for returned stack addresses, local blocks,
2150  // label addresses or references to temporaries.
2151  if (lhsType->isPointerType() ||
2152      (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
2153    stackE = EvalAddr(RetValExp, refVars);
2154  } else if (lhsType->isReferenceType()) {
2155    stackE = EvalVal(RetValExp, refVars);
2156  }
2157
2158  if (stackE == 0)
2159    return; // Nothing suspicious was found.
2160
2161  SourceLocation diagLoc;
2162  SourceRange diagRange;
2163  if (refVars.empty()) {
2164    diagLoc = stackE->getLocStart();
2165    diagRange = stackE->getSourceRange();
2166  } else {
2167    // We followed through a reference variable. 'stackE' contains the
2168    // problematic expression but we will warn at the return statement pointing
2169    // at the reference variable. We will later display the "trail" of
2170    // reference variables using notes.
2171    diagLoc = refVars[0]->getLocStart();
2172    diagRange = refVars[0]->getSourceRange();
2173  }
2174
2175  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2176    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2177                                             : diag::warn_ret_stack_addr)
2178     << DR->getDecl()->getDeclName() << diagRange;
2179  } else if (isa<BlockExpr>(stackE)) { // local block.
2180    Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2181  } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2182    Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2183  } else { // local temporary.
2184    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2185                                             : diag::warn_ret_local_temp_addr)
2186     << diagRange;
2187  }
2188
2189  // Display the "trail" of reference variables that we followed until we
2190  // found the problematic expression using notes.
2191  for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2192    VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2193    // If this var binds to another reference var, show the range of the next
2194    // var, otherwise the var binds to the problematic expression, in which case
2195    // show the range of the expression.
2196    SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2197                                  : stackE->getSourceRange();
2198    Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2199      << VD->getDeclName() << range;
2200  }
2201}
2202
2203/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2204///  check if the expression in a return statement evaluates to an address
2205///  to a location on the stack, a local block, an address of a label, or a
2206///  reference to local temporary. The recursion is used to traverse the
2207///  AST of the return expression, with recursion backtracking when we
2208///  encounter a subexpression that (1) clearly does not lead to one of the
2209///  above problematic expressions (2) is something we cannot determine leads to
2210///  a problematic expression based on such local checking.
2211///
2212///  Both EvalAddr and EvalVal follow through reference variables to evaluate
2213///  the expression that they point to. Such variables are added to the
2214///  'refVars' vector so that we know what the reference variable "trail" was.
2215///
2216///  EvalAddr processes expressions that are pointers that are used as
2217///  references (and not L-values).  EvalVal handles all other values.
2218///  At the base case of the recursion is a check for the above problematic
2219///  expressions.
2220///
2221///  This implementation handles:
2222///
2223///   * pointer-to-pointer casts
2224///   * implicit conversions from array references to pointers
2225///   * taking the address of fields
2226///   * arbitrary interplay between "&" and "*" operators
2227///   * pointer arithmetic from an address of a stack variable
2228///   * taking the address of an array element where the array is on the stack
2229static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2230  if (E->isTypeDependent())
2231      return NULL;
2232
2233  // We should only be called for evaluating pointer expressions.
2234  assert((E->getType()->isAnyPointerType() ||
2235          E->getType()->isBlockPointerType() ||
2236          E->getType()->isObjCQualifiedIdType()) &&
2237         "EvalAddr only works on pointers");
2238
2239  E = E->IgnoreParens();
2240
2241  // Our "symbolic interpreter" is just a dispatch off the currently
2242  // viewed AST node.  We then recursively traverse the AST by calling
2243  // EvalAddr and EvalVal appropriately.
2244  switch (E->getStmtClass()) {
2245  case Stmt::DeclRefExprClass: {
2246    DeclRefExpr *DR = cast<DeclRefExpr>(E);
2247
2248    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2249      // If this is a reference variable, follow through to the expression that
2250      // it points to.
2251      if (V->hasLocalStorage() &&
2252          V->getType()->isReferenceType() && V->hasInit()) {
2253        // Add the reference variable to the "trail".
2254        refVars.push_back(DR);
2255        return EvalAddr(V->getInit(), refVars);
2256      }
2257
2258    return NULL;
2259  }
2260
2261  case Stmt::UnaryOperatorClass: {
2262    // The only unary operator that make sense to handle here
2263    // is AddrOf.  All others don't make sense as pointers.
2264    UnaryOperator *U = cast<UnaryOperator>(E);
2265
2266    if (U->getOpcode() == UO_AddrOf)
2267      return EvalVal(U->getSubExpr(), refVars);
2268    else
2269      return NULL;
2270  }
2271
2272  case Stmt::BinaryOperatorClass: {
2273    // Handle pointer arithmetic.  All other binary operators are not valid
2274    // in this context.
2275    BinaryOperator *B = cast<BinaryOperator>(E);
2276    BinaryOperatorKind op = B->getOpcode();
2277
2278    if (op != BO_Add && op != BO_Sub)
2279      return NULL;
2280
2281    Expr *Base = B->getLHS();
2282
2283    // Determine which argument is the real pointer base.  It could be
2284    // the RHS argument instead of the LHS.
2285    if (!Base->getType()->isPointerType()) Base = B->getRHS();
2286
2287    assert (Base->getType()->isPointerType());
2288    return EvalAddr(Base, refVars);
2289  }
2290
2291  // For conditional operators we need to see if either the LHS or RHS are
2292  // valid DeclRefExpr*s.  If one of them is valid, we return it.
2293  case Stmt::ConditionalOperatorClass: {
2294    ConditionalOperator *C = cast<ConditionalOperator>(E);
2295
2296    // Handle the GNU extension for missing LHS.
2297    if (Expr *lhsExpr = C->getLHS()) {
2298    // In C++, we can have a throw-expression, which has 'void' type.
2299      if (!lhsExpr->getType()->isVoidType())
2300        if (Expr* LHS = EvalAddr(lhsExpr, refVars))
2301          return LHS;
2302    }
2303
2304    // In C++, we can have a throw-expression, which has 'void' type.
2305    if (C->getRHS()->getType()->isVoidType())
2306      return NULL;
2307
2308    return EvalAddr(C->getRHS(), refVars);
2309  }
2310
2311  case Stmt::BlockExprClass:
2312    if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
2313      return E; // local block.
2314    return NULL;
2315
2316  case Stmt::AddrLabelExprClass:
2317    return E; // address of label.
2318
2319  // For casts, we need to handle conversions from arrays to
2320  // pointer values, and pointer-to-pointer conversions.
2321  case Stmt::ImplicitCastExprClass:
2322  case Stmt::CStyleCastExprClass:
2323  case Stmt::CXXFunctionalCastExprClass:
2324  case Stmt::ObjCBridgedCastExprClass: {
2325    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2326    QualType T = SubExpr->getType();
2327
2328    if (SubExpr->getType()->isPointerType() ||
2329        SubExpr->getType()->isBlockPointerType() ||
2330        SubExpr->getType()->isObjCQualifiedIdType())
2331      return EvalAddr(SubExpr, refVars);
2332    else if (T->isArrayType())
2333      return EvalVal(SubExpr, refVars);
2334    else
2335      return 0;
2336  }
2337
2338  // C++ casts.  For dynamic casts, static casts, and const casts, we
2339  // are always converting from a pointer-to-pointer, so we just blow
2340  // through the cast.  In the case the dynamic cast doesn't fail (and
2341  // return NULL), we take the conservative route and report cases
2342  // where we return the address of a stack variable.  For Reinterpre
2343  // FIXME: The comment about is wrong; we're not always converting
2344  // from pointer to pointer. I'm guessing that this code should also
2345  // handle references to objects.
2346  case Stmt::CXXStaticCastExprClass:
2347  case Stmt::CXXDynamicCastExprClass:
2348  case Stmt::CXXConstCastExprClass:
2349  case Stmt::CXXReinterpretCastExprClass: {
2350      Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
2351      if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
2352        return EvalAddr(S, refVars);
2353      else
2354        return NULL;
2355  }
2356
2357  case Stmt::MaterializeTemporaryExprClass:
2358    if (Expr *Result = EvalAddr(
2359                         cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2360                                refVars))
2361      return Result;
2362
2363    return E;
2364
2365  // Everything else: we simply don't reason about them.
2366  default:
2367    return NULL;
2368  }
2369}
2370
2371
2372///  EvalVal - This function is complements EvalAddr in the mutual recursion.
2373///   See the comments for EvalAddr for more details.
2374static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2375do {
2376  // We should only be called for evaluating non-pointer expressions, or
2377  // expressions with a pointer type that are not used as references but instead
2378  // are l-values (e.g., DeclRefExpr with a pointer type).
2379
2380  // Our "symbolic interpreter" is just a dispatch off the currently
2381  // viewed AST node.  We then recursively traverse the AST by calling
2382  // EvalAddr and EvalVal appropriately.
2383
2384  E = E->IgnoreParens();
2385  switch (E->getStmtClass()) {
2386  case Stmt::ImplicitCastExprClass: {
2387    ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
2388    if (IE->getValueKind() == VK_LValue) {
2389      E = IE->getSubExpr();
2390      continue;
2391    }
2392    return NULL;
2393  }
2394
2395  case Stmt::DeclRefExprClass: {
2396    // When we hit a DeclRefExpr we are looking at code that refers to a
2397    // variable's name. If it's not a reference variable we check if it has
2398    // local storage within the function, and if so, return the expression.
2399    DeclRefExpr *DR = cast<DeclRefExpr>(E);
2400
2401    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2402      if (V->hasLocalStorage()) {
2403        if (!V->getType()->isReferenceType())
2404          return DR;
2405
2406        // Reference variable, follow through to the expression that
2407        // it points to.
2408        if (V->hasInit()) {
2409          // Add the reference variable to the "trail".
2410          refVars.push_back(DR);
2411          return EvalVal(V->getInit(), refVars);
2412        }
2413      }
2414
2415    return NULL;
2416  }
2417
2418  case Stmt::UnaryOperatorClass: {
2419    // The only unary operator that make sense to handle here
2420    // is Deref.  All others don't resolve to a "name."  This includes
2421    // handling all sorts of rvalues passed to a unary operator.
2422    UnaryOperator *U = cast<UnaryOperator>(E);
2423
2424    if (U->getOpcode() == UO_Deref)
2425      return EvalAddr(U->getSubExpr(), refVars);
2426
2427    return NULL;
2428  }
2429
2430  case Stmt::ArraySubscriptExprClass: {
2431    // Array subscripts are potential references to data on the stack.  We
2432    // retrieve the DeclRefExpr* for the array variable if it indeed
2433    // has local storage.
2434    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
2435  }
2436
2437  case Stmt::ConditionalOperatorClass: {
2438    // For conditional operators we need to see if either the LHS or RHS are
2439    // non-NULL Expr's.  If one is non-NULL, we return it.
2440    ConditionalOperator *C = cast<ConditionalOperator>(E);
2441
2442    // Handle the GNU extension for missing LHS.
2443    if (Expr *lhsExpr = C->getLHS())
2444      if (Expr *LHS = EvalVal(lhsExpr, refVars))
2445        return LHS;
2446
2447    return EvalVal(C->getRHS(), refVars);
2448  }
2449
2450  // Accesses to members are potential references to data on the stack.
2451  case Stmt::MemberExprClass: {
2452    MemberExpr *M = cast<MemberExpr>(E);
2453
2454    // Check for indirect access.  We only want direct field accesses.
2455    if (M->isArrow())
2456      return NULL;
2457
2458    // Check whether the member type is itself a reference, in which case
2459    // we're not going to refer to the member, but to what the member refers to.
2460    if (M->getMemberDecl()->getType()->isReferenceType())
2461      return NULL;
2462
2463    return EvalVal(M->getBase(), refVars);
2464  }
2465
2466  case Stmt::MaterializeTemporaryExprClass:
2467    if (Expr *Result = EvalVal(
2468                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2469                               refVars))
2470      return Result;
2471
2472    return E;
2473
2474  default:
2475    // Check that we don't return or take the address of a reference to a
2476    // temporary. This is only useful in C++.
2477    if (!E->isTypeDependent() && E->isRValue())
2478      return E;
2479
2480    // Everything else: we simply don't reason about them.
2481    return NULL;
2482  }
2483} while (true);
2484}
2485
2486//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2487
2488/// Check for comparisons of floating point operands using != and ==.
2489/// Issue a warning if these are no self-comparisons, as they are not likely
2490/// to do what the programmer intended.
2491void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2492  bool EmitWarning = true;
2493
2494  Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2495  Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
2496
2497  // Special case: check for x == x (which is OK).
2498  // Do not emit warnings for such cases.
2499  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2500    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2501      if (DRL->getDecl() == DRR->getDecl())
2502        EmitWarning = false;
2503
2504
2505  // Special case: check for comparisons against literals that can be exactly
2506  //  represented by APFloat.  In such cases, do not emit a warning.  This
2507  //  is a heuristic: often comparison against such literals are used to
2508  //  detect if a value in a variable has not changed.  This clearly can
2509  //  lead to false negatives.
2510  if (EmitWarning) {
2511    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2512      if (FLL->isExact())
2513        EmitWarning = false;
2514    } else
2515      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2516        if (FLR->isExact())
2517          EmitWarning = false;
2518    }
2519  }
2520
2521  // Check for comparisons with builtin types.
2522  if (EmitWarning)
2523    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
2524      if (CL->isBuiltinCall(Context))
2525        EmitWarning = false;
2526
2527  if (EmitWarning)
2528    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
2529      if (CR->isBuiltinCall(Context))
2530        EmitWarning = false;
2531
2532  // Emit the diagnostic.
2533  if (EmitWarning)
2534    Diag(loc, diag::warn_floatingpoint_eq)
2535      << lex->getSourceRange() << rex->getSourceRange();
2536}
2537
2538//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2539//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2540
2541namespace {
2542
2543/// Structure recording the 'active' range of an integer-valued
2544/// expression.
2545struct IntRange {
2546  /// The number of bits active in the int.
2547  unsigned Width;
2548
2549  /// True if the int is known not to have negative values.
2550  bool NonNegative;
2551
2552  IntRange(unsigned Width, bool NonNegative)
2553    : Width(Width), NonNegative(NonNegative)
2554  {}
2555
2556  /// Returns the range of the bool type.
2557  static IntRange forBoolType() {
2558    return IntRange(1, true);
2559  }
2560
2561  /// Returns the range of an opaque value of the given integral type.
2562  static IntRange forValueOfType(ASTContext &C, QualType T) {
2563    return forValueOfCanonicalType(C,
2564                          T->getCanonicalTypeInternal().getTypePtr());
2565  }
2566
2567  /// Returns the range of an opaque value of a canonical integral type.
2568  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
2569    assert(T->isCanonicalUnqualified());
2570
2571    if (const VectorType *VT = dyn_cast<VectorType>(T))
2572      T = VT->getElementType().getTypePtr();
2573    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2574      T = CT->getElementType().getTypePtr();
2575
2576    // For enum types, use the known bit width of the enumerators.
2577    if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2578      EnumDecl *Enum = ET->getDecl();
2579      if (!Enum->isDefinition())
2580        return IntRange(C.getIntWidth(QualType(T, 0)), false);
2581
2582      unsigned NumPositive = Enum->getNumPositiveBits();
2583      unsigned NumNegative = Enum->getNumNegativeBits();
2584
2585      return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2586    }
2587
2588    const BuiltinType *BT = cast<BuiltinType>(T);
2589    assert(BT->isInteger());
2590
2591    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2592  }
2593
2594  /// Returns the "target" range of a canonical integral type, i.e.
2595  /// the range of values expressible in the type.
2596  ///
2597  /// This matches forValueOfCanonicalType except that enums have the
2598  /// full range of their type, not the range of their enumerators.
2599  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2600    assert(T->isCanonicalUnqualified());
2601
2602    if (const VectorType *VT = dyn_cast<VectorType>(T))
2603      T = VT->getElementType().getTypePtr();
2604    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2605      T = CT->getElementType().getTypePtr();
2606    if (const EnumType *ET = dyn_cast<EnumType>(T))
2607      T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
2608
2609    const BuiltinType *BT = cast<BuiltinType>(T);
2610    assert(BT->isInteger());
2611
2612    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2613  }
2614
2615  /// Returns the supremum of two ranges: i.e. their conservative merge.
2616  static IntRange join(IntRange L, IntRange R) {
2617    return IntRange(std::max(L.Width, R.Width),
2618                    L.NonNegative && R.NonNegative);
2619  }
2620
2621  /// Returns the infinum of two ranges: i.e. their aggressive merge.
2622  static IntRange meet(IntRange L, IntRange R) {
2623    return IntRange(std::min(L.Width, R.Width),
2624                    L.NonNegative || R.NonNegative);
2625  }
2626};
2627
2628IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2629  if (value.isSigned() && value.isNegative())
2630    return IntRange(value.getMinSignedBits(), false);
2631
2632  if (value.getBitWidth() > MaxWidth)
2633    value = value.trunc(MaxWidth);
2634
2635  // isNonNegative() just checks the sign bit without considering
2636  // signedness.
2637  return IntRange(value.getActiveBits(), true);
2638}
2639
2640IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
2641                       unsigned MaxWidth) {
2642  if (result.isInt())
2643    return GetValueRange(C, result.getInt(), MaxWidth);
2644
2645  if (result.isVector()) {
2646    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2647    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2648      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2649      R = IntRange::join(R, El);
2650    }
2651    return R;
2652  }
2653
2654  if (result.isComplexInt()) {
2655    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2656    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2657    return IntRange::join(R, I);
2658  }
2659
2660  // This can happen with lossless casts to intptr_t of "based" lvalues.
2661  // Assume it might use arbitrary bits.
2662  // FIXME: The only reason we need to pass the type in here is to get
2663  // the sign right on this one case.  It would be nice if APValue
2664  // preserved this.
2665  assert(result.isLValue());
2666  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
2667}
2668
2669/// Pseudo-evaluate the given integer expression, estimating the
2670/// range of values it might take.
2671///
2672/// \param MaxWidth - the width to which the value will be truncated
2673IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2674  E = E->IgnoreParens();
2675
2676  // Try a full evaluation first.
2677  Expr::EvalResult result;
2678  if (E->Evaluate(result, C))
2679    return GetValueRange(C, result.Val, E->getType(), MaxWidth);
2680
2681  // I think we only want to look through implicit casts here; if the
2682  // user has an explicit widening cast, we should treat the value as
2683  // being of the new, wider type.
2684  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
2685    if (CE->getCastKind() == CK_NoOp)
2686      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2687
2688    IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
2689
2690    bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
2691
2692    // Assume that non-integer casts can span the full range of the type.
2693    if (!isIntegerCast)
2694      return OutputTypeRange;
2695
2696    IntRange SubRange
2697      = GetExprRange(C, CE->getSubExpr(),
2698                     std::min(MaxWidth, OutputTypeRange.Width));
2699
2700    // Bail out if the subexpr's range is as wide as the cast type.
2701    if (SubRange.Width >= OutputTypeRange.Width)
2702      return OutputTypeRange;
2703
2704    // Otherwise, we take the smaller width, and we're non-negative if
2705    // either the output type or the subexpr is.
2706    return IntRange(SubRange.Width,
2707                    SubRange.NonNegative || OutputTypeRange.NonNegative);
2708  }
2709
2710  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2711    // If we can fold the condition, just take that operand.
2712    bool CondResult;
2713    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2714      return GetExprRange(C, CondResult ? CO->getTrueExpr()
2715                                        : CO->getFalseExpr(),
2716                          MaxWidth);
2717
2718    // Otherwise, conservatively merge.
2719    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2720    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2721    return IntRange::join(L, R);
2722  }
2723
2724  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2725    switch (BO->getOpcode()) {
2726
2727    // Boolean-valued operations are single-bit and positive.
2728    case BO_LAnd:
2729    case BO_LOr:
2730    case BO_LT:
2731    case BO_GT:
2732    case BO_LE:
2733    case BO_GE:
2734    case BO_EQ:
2735    case BO_NE:
2736      return IntRange::forBoolType();
2737
2738    // The type of the assignments is the type of the LHS, so the RHS
2739    // is not necessarily the same type.
2740    case BO_MulAssign:
2741    case BO_DivAssign:
2742    case BO_RemAssign:
2743    case BO_AddAssign:
2744    case BO_SubAssign:
2745    case BO_XorAssign:
2746    case BO_OrAssign:
2747      // TODO: bitfields?
2748      return IntRange::forValueOfType(C, E->getType());
2749
2750    // Simple assignments just pass through the RHS, which will have
2751    // been coerced to the LHS type.
2752    case BO_Assign:
2753      // TODO: bitfields?
2754      return GetExprRange(C, BO->getRHS(), MaxWidth);
2755
2756    // Operations with opaque sources are black-listed.
2757    case BO_PtrMemD:
2758    case BO_PtrMemI:
2759      return IntRange::forValueOfType(C, E->getType());
2760
2761    // Bitwise-and uses the *infinum* of the two source ranges.
2762    case BO_And:
2763    case BO_AndAssign:
2764      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2765                            GetExprRange(C, BO->getRHS(), MaxWidth));
2766
2767    // Left shift gets black-listed based on a judgement call.
2768    case BO_Shl:
2769      // ...except that we want to treat '1 << (blah)' as logically
2770      // positive.  It's an important idiom.
2771      if (IntegerLiteral *I
2772            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2773        if (I->getValue() == 1) {
2774          IntRange R = IntRange::forValueOfType(C, E->getType());
2775          return IntRange(R.Width, /*NonNegative*/ true);
2776        }
2777      }
2778      // fallthrough
2779
2780    case BO_ShlAssign:
2781      return IntRange::forValueOfType(C, E->getType());
2782
2783    // Right shift by a constant can narrow its left argument.
2784    case BO_Shr:
2785    case BO_ShrAssign: {
2786      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2787
2788      // If the shift amount is a positive constant, drop the width by
2789      // that much.
2790      llvm::APSInt shift;
2791      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2792          shift.isNonNegative()) {
2793        unsigned zext = shift.getZExtValue();
2794        if (zext >= L.Width)
2795          L.Width = (L.NonNegative ? 0 : 1);
2796        else
2797          L.Width -= zext;
2798      }
2799
2800      return L;
2801    }
2802
2803    // Comma acts as its right operand.
2804    case BO_Comma:
2805      return GetExprRange(C, BO->getRHS(), MaxWidth);
2806
2807    // Black-list pointer subtractions.
2808    case BO_Sub:
2809      if (BO->getLHS()->getType()->isPointerType())
2810        return IntRange::forValueOfType(C, E->getType());
2811      break;
2812
2813    // The width of a division result is mostly determined by the size
2814    // of the LHS.
2815    case BO_Div: {
2816      // Don't 'pre-truncate' the operands.
2817      unsigned opWidth = C.getIntWidth(E->getType());
2818      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2819
2820      // If the divisor is constant, use that.
2821      llvm::APSInt divisor;
2822      if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
2823        unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
2824        if (log2 >= L.Width)
2825          L.Width = (L.NonNegative ? 0 : 1);
2826        else
2827          L.Width = std::min(L.Width - log2, MaxWidth);
2828        return L;
2829      }
2830
2831      // Otherwise, just use the LHS's width.
2832      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2833      return IntRange(L.Width, L.NonNegative && R.NonNegative);
2834    }
2835
2836    // The result of a remainder can't be larger than the result of
2837    // either side.
2838    case BO_Rem: {
2839      // Don't 'pre-truncate' the operands.
2840      unsigned opWidth = C.getIntWidth(E->getType());
2841      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2842      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2843
2844      IntRange meet = IntRange::meet(L, R);
2845      meet.Width = std::min(meet.Width, MaxWidth);
2846      return meet;
2847    }
2848
2849    // The default behavior is okay for these.
2850    case BO_Mul:
2851    case BO_Add:
2852    case BO_Xor:
2853    case BO_Or:
2854      break;
2855    }
2856
2857    // The default case is to treat the operation as if it were closed
2858    // on the narrowest type that encompasses both operands.
2859    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2860    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2861    return IntRange::join(L, R);
2862  }
2863
2864  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2865    switch (UO->getOpcode()) {
2866    // Boolean-valued operations are white-listed.
2867    case UO_LNot:
2868      return IntRange::forBoolType();
2869
2870    // Operations with opaque sources are black-listed.
2871    case UO_Deref:
2872    case UO_AddrOf: // should be impossible
2873      return IntRange::forValueOfType(C, E->getType());
2874
2875    default:
2876      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2877    }
2878  }
2879
2880  if (dyn_cast<OffsetOfExpr>(E)) {
2881    IntRange::forValueOfType(C, E->getType());
2882  }
2883
2884  FieldDecl *BitField = E->getBitField();
2885  if (BitField) {
2886    llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2887    unsigned BitWidth = BitWidthAP.getZExtValue();
2888
2889    return IntRange(BitWidth,
2890                    BitField->getType()->isUnsignedIntegerOrEnumerationType());
2891  }
2892
2893  return IntRange::forValueOfType(C, E->getType());
2894}
2895
2896IntRange GetExprRange(ASTContext &C, Expr *E) {
2897  return GetExprRange(C, E, C.getIntWidth(E->getType()));
2898}
2899
2900/// Checks whether the given value, which currently has the given
2901/// source semantics, has the same value when coerced through the
2902/// target semantics.
2903bool IsSameFloatAfterCast(const llvm::APFloat &value,
2904                          const llvm::fltSemantics &Src,
2905                          const llvm::fltSemantics &Tgt) {
2906  llvm::APFloat truncated = value;
2907
2908  bool ignored;
2909  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2910  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2911
2912  return truncated.bitwiseIsEqual(value);
2913}
2914
2915/// Checks whether the given value, which currently has the given
2916/// source semantics, has the same value when coerced through the
2917/// target semantics.
2918///
2919/// The value might be a vector of floats (or a complex number).
2920bool IsSameFloatAfterCast(const APValue &value,
2921                          const llvm::fltSemantics &Src,
2922                          const llvm::fltSemantics &Tgt) {
2923  if (value.isFloat())
2924    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2925
2926  if (value.isVector()) {
2927    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2928      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2929        return false;
2930    return true;
2931  }
2932
2933  assert(value.isComplexFloat());
2934  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2935          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2936}
2937
2938void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
2939
2940static bool IsZero(Sema &S, Expr *E) {
2941  // Suppress cases where we are comparing against an enum constant.
2942  if (const DeclRefExpr *DR =
2943      dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2944    if (isa<EnumConstantDecl>(DR->getDecl()))
2945      return false;
2946
2947  // Suppress cases where the '0' value is expanded from a macro.
2948  if (E->getLocStart().isMacroID())
2949    return false;
2950
2951  llvm::APSInt Value;
2952  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2953}
2954
2955static bool HasEnumType(Expr *E) {
2956  // Strip off implicit integral promotions.
2957  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2958    if (ICE->getCastKind() != CK_IntegralCast &&
2959        ICE->getCastKind() != CK_NoOp)
2960      break;
2961    E = ICE->getSubExpr();
2962  }
2963
2964  return E->getType()->isEnumeralType();
2965}
2966
2967void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
2968  BinaryOperatorKind op = E->getOpcode();
2969  if (E->isValueDependent())
2970    return;
2971
2972  if (op == BO_LT && IsZero(S, E->getRHS())) {
2973    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2974      << "< 0" << "false" << HasEnumType(E->getLHS())
2975      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2976  } else if (op == BO_GE && IsZero(S, E->getRHS())) {
2977    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2978      << ">= 0" << "true" << HasEnumType(E->getLHS())
2979      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2980  } else if (op == BO_GT && IsZero(S, E->getLHS())) {
2981    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2982      << "0 >" << "false" << HasEnumType(E->getRHS())
2983      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2984  } else if (op == BO_LE && IsZero(S, E->getLHS())) {
2985    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2986      << "0 <=" << "true" << HasEnumType(E->getRHS())
2987      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2988  }
2989}
2990
2991/// Analyze the operands of the given comparison.  Implements the
2992/// fallback case from AnalyzeComparison.
2993void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2994  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2995  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2996}
2997
2998/// \brief Implements -Wsign-compare.
2999///
3000/// \param lex the left-hand expression
3001/// \param rex the right-hand expression
3002/// \param OpLoc the location of the joining operator
3003/// \param BinOpc binary opcode or 0
3004void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3005  // The type the comparison is being performed in.
3006  QualType T = E->getLHS()->getType();
3007  assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3008         && "comparison with mismatched types");
3009
3010  // We don't do anything special if this isn't an unsigned integral
3011  // comparison:  we're only interested in integral comparisons, and
3012  // signed comparisons only happen in cases we don't care to warn about.
3013  //
3014  // We also don't care about value-dependent expressions or expressions
3015  // whose result is a constant.
3016  if (!T->hasUnsignedIntegerRepresentation()
3017      || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
3018    return AnalyzeImpConvsInComparison(S, E);
3019
3020  Expr *lex = E->getLHS()->IgnoreParenImpCasts();
3021  Expr *rex = E->getRHS()->IgnoreParenImpCasts();
3022
3023  // Check to see if one of the (unmodified) operands is of different
3024  // signedness.
3025  Expr *signedOperand, *unsignedOperand;
3026  if (lex->getType()->hasSignedIntegerRepresentation()) {
3027    assert(!rex->getType()->hasSignedIntegerRepresentation() &&
3028           "unsigned comparison between two signed integer expressions?");
3029    signedOperand = lex;
3030    unsignedOperand = rex;
3031  } else if (rex->getType()->hasSignedIntegerRepresentation()) {
3032    signedOperand = rex;
3033    unsignedOperand = lex;
3034  } else {
3035    CheckTrivialUnsignedComparison(S, E);
3036    return AnalyzeImpConvsInComparison(S, E);
3037  }
3038
3039  // Otherwise, calculate the effective range of the signed operand.
3040  IntRange signedRange = GetExprRange(S.Context, signedOperand);
3041
3042  // Go ahead and analyze implicit conversions in the operands.  Note
3043  // that we skip the implicit conversions on both sides.
3044  AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
3045  AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
3046
3047  // If the signed range is non-negative, -Wsign-compare won't fire,
3048  // but we should still check for comparisons which are always true
3049  // or false.
3050  if (signedRange.NonNegative)
3051    return CheckTrivialUnsignedComparison(S, E);
3052
3053  // For (in)equality comparisons, if the unsigned operand is a
3054  // constant which cannot collide with a overflowed signed operand,
3055  // then reinterpreting the signed operand as unsigned will not
3056  // change the result of the comparison.
3057  if (E->isEqualityOp()) {
3058    unsigned comparisonWidth = S.Context.getIntWidth(T);
3059    IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
3060
3061    // We should never be unable to prove that the unsigned operand is
3062    // non-negative.
3063    assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3064
3065    if (unsignedRange.Width < comparisonWidth)
3066      return;
3067  }
3068
3069  S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3070    << lex->getType() << rex->getType()
3071    << lex->getSourceRange() << rex->getSourceRange();
3072}
3073
3074/// Analyzes an attempt to assign the given value to a bitfield.
3075///
3076/// Returns true if there was something fishy about the attempt.
3077bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3078                               SourceLocation InitLoc) {
3079  assert(Bitfield->isBitField());
3080  if (Bitfield->isInvalidDecl())
3081    return false;
3082
3083  // White-list bool bitfields.
3084  if (Bitfield->getType()->isBooleanType())
3085    return false;
3086
3087  // Ignore value- or type-dependent expressions.
3088  if (Bitfield->getBitWidth()->isValueDependent() ||
3089      Bitfield->getBitWidth()->isTypeDependent() ||
3090      Init->isValueDependent() ||
3091      Init->isTypeDependent())
3092    return false;
3093
3094  Expr *OriginalInit = Init->IgnoreParenImpCasts();
3095
3096  llvm::APSInt Width(32);
3097  Expr::EvalResult InitValue;
3098  if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
3099      !OriginalInit->Evaluate(InitValue, S.Context) ||
3100      !InitValue.Val.isInt())
3101    return false;
3102
3103  const llvm::APSInt &Value = InitValue.Val.getInt();
3104  unsigned OriginalWidth = Value.getBitWidth();
3105  unsigned FieldWidth = Width.getZExtValue();
3106
3107  if (OriginalWidth <= FieldWidth)
3108    return false;
3109
3110  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
3111
3112  // It's fairly common to write values into signed bitfields
3113  // that, if sign-extended, would end up becoming a different
3114  // value.  We don't want to warn about that.
3115  if (Value.isSigned() && Value.isNegative())
3116    TruncatedValue = TruncatedValue.sext(OriginalWidth);
3117  else
3118    TruncatedValue = TruncatedValue.zext(OriginalWidth);
3119
3120  if (Value == TruncatedValue)
3121    return false;
3122
3123  std::string PrettyValue = Value.toString(10);
3124  std::string PrettyTrunc = TruncatedValue.toString(10);
3125
3126  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3127    << PrettyValue << PrettyTrunc << OriginalInit->getType()
3128    << Init->getSourceRange();
3129
3130  return true;
3131}
3132
3133/// Analyze the given simple or compound assignment for warning-worthy
3134/// operations.
3135void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3136  // Just recurse on the LHS.
3137  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3138
3139  // We want to recurse on the RHS as normal unless we're assigning to
3140  // a bitfield.
3141  if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
3142    if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3143                                  E->getOperatorLoc())) {
3144      // Recurse, ignoring any implicit conversions on the RHS.
3145      return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3146                                        E->getOperatorLoc());
3147    }
3148  }
3149
3150  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3151}
3152
3153/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3154void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3155                     SourceLocation CContext, unsigned diag) {
3156  S.Diag(E->getExprLoc(), diag)
3157    << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3158}
3159
3160/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3161void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3162                     unsigned diag) {
3163  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3164}
3165
3166/// Diagnose an implicit cast from a literal expression. Also attemps to supply
3167/// fixit hints when the cast wouldn't lose information to simply write the
3168/// expression with the expected type.
3169void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3170                                    SourceLocation CContext) {
3171  // Emit the primary warning first, then try to emit a fixit hint note if
3172  // reasonable.
3173  S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3174    << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3175
3176  const llvm::APFloat &Value = FL->getValue();
3177
3178  // Don't attempt to fix PPC double double literals.
3179  if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
3180    return;
3181
3182  // Try to convert this exactly to an integer.
3183  bool isExact = false;
3184  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3185                            T->hasUnsignedIntegerRepresentation());
3186  if (Value.convertToInteger(IntegerValue,
3187                             llvm::APFloat::rmTowardZero, &isExact)
3188      != llvm::APFloat::opOK || !isExact)
3189    return;
3190
3191  std::string LiteralValue = IntegerValue.toString(10);
3192  S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
3193    << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
3194}
3195
3196std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3197  if (!Range.Width) return "0";
3198
3199  llvm::APSInt ValueInRange = Value;
3200  ValueInRange.setIsSigned(!Range.NonNegative);
3201  ValueInRange = ValueInRange.trunc(Range.Width);
3202  return ValueInRange.toString(10);
3203}
3204
3205static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3206  SourceManager &smgr = S.Context.getSourceManager();
3207  return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3208}
3209
3210void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
3211                             SourceLocation CC, bool *ICContext = 0) {
3212  if (E->isTypeDependent() || E->isValueDependent()) return;
3213
3214  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3215  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3216  if (Source == Target) return;
3217  if (Target->isDependentType()) return;
3218
3219  // If the conversion context location is invalid don't complain. We also
3220  // don't want to emit a warning if the issue occurs from the expansion of
3221  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3222  // delay this check as long as possible. Once we detect we are in that
3223  // scenario, we just return.
3224  if (CC.isInvalid())
3225    return;
3226
3227  // Never diagnose implicit casts to bool.
3228  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
3229    return;
3230
3231  // Strip vector types.
3232  if (isa<VectorType>(Source)) {
3233    if (!isa<VectorType>(Target)) {
3234      if (isFromSystemMacro(S, CC))
3235        return;
3236      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
3237    }
3238
3239    // If the vector cast is cast between two vectors of the same size, it is
3240    // a bitcast, not a conversion.
3241    if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3242      return;
3243
3244    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3245    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3246  }
3247
3248  // Strip complex types.
3249  if (isa<ComplexType>(Source)) {
3250    if (!isa<ComplexType>(Target)) {
3251      if (isFromSystemMacro(S, CC))
3252        return;
3253
3254      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
3255    }
3256
3257    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3258    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3259  }
3260
3261  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3262  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3263
3264  // If the source is floating point...
3265  if (SourceBT && SourceBT->isFloatingPoint()) {
3266    // ...and the target is floating point...
3267    if (TargetBT && TargetBT->isFloatingPoint()) {
3268      // ...then warn if we're dropping FP rank.
3269
3270      // Builtin FP kinds are ordered by increasing FP rank.
3271      if (SourceBT->getKind() > TargetBT->getKind()) {
3272        // Don't warn about float constants that are precisely
3273        // representable in the target type.
3274        Expr::EvalResult result;
3275        if (E->Evaluate(result, S.Context)) {
3276          // Value might be a float, a float vector, or a float complex.
3277          if (IsSameFloatAfterCast(result.Val,
3278                   S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3279                   S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
3280            return;
3281        }
3282
3283        if (isFromSystemMacro(S, CC))
3284          return;
3285
3286        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
3287      }
3288      return;
3289    }
3290
3291    // If the target is integral, always warn.
3292    if ((TargetBT && TargetBT->isInteger())) {
3293      if (isFromSystemMacro(S, CC))
3294        return;
3295
3296      Expr *InnerE = E->IgnoreParenImpCasts();
3297      // We also want to warn on, e.g., "int i = -1.234"
3298      if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3299        if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3300          InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3301
3302      if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3303        DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
3304      } else {
3305        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3306      }
3307    }
3308
3309    return;
3310  }
3311
3312  if (!Source->isIntegerType() || !Target->isIntegerType())
3313    return;
3314
3315  if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3316           == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3317    S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3318        << E->getSourceRange() << clang::SourceRange(CC);
3319    return;
3320  }
3321
3322  IntRange SourceRange = GetExprRange(S.Context, E);
3323  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
3324
3325  if (SourceRange.Width > TargetRange.Width) {
3326    // If the source is a constant, use a default-on diagnostic.
3327    // TODO: this should happen for bitfield stores, too.
3328    llvm::APSInt Value(32);
3329    if (E->isIntegerConstantExpr(Value, S.Context)) {
3330      if (isFromSystemMacro(S, CC))
3331        return;
3332
3333      std::string PrettySourceValue = Value.toString(10);
3334      std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3335
3336      S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3337        << PrettySourceValue << PrettyTargetValue
3338        << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3339      return;
3340    }
3341
3342    // People want to build with -Wshorten-64-to-32 and not -Wconversion.
3343    if (isFromSystemMacro(S, CC))
3344      return;
3345
3346    if (SourceRange.Width == 64 && TargetRange.Width == 32)
3347      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3348    return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
3349  }
3350
3351  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3352      (!TargetRange.NonNegative && SourceRange.NonNegative &&
3353       SourceRange.Width == TargetRange.Width)) {
3354
3355    if (isFromSystemMacro(S, CC))
3356      return;
3357
3358    unsigned DiagID = diag::warn_impcast_integer_sign;
3359
3360    // Traditionally, gcc has warned about this under -Wsign-compare.
3361    // We also want to warn about it in -Wconversion.
3362    // So if -Wconversion is off, use a completely identical diagnostic
3363    // in the sign-compare group.
3364    // The conditional-checking code will
3365    if (ICContext) {
3366      DiagID = diag::warn_impcast_integer_sign_conditional;
3367      *ICContext = true;
3368    }
3369
3370    return DiagnoseImpCast(S, E, T, CC, DiagID);
3371  }
3372
3373  // Diagnose conversions between different enumeration types.
3374  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3375  // type, to give us better diagnostics.
3376  QualType SourceType = E->getType();
3377  if (!S.getLangOptions().CPlusPlus) {
3378    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3379      if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3380        EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3381        SourceType = S.Context.getTypeDeclType(Enum);
3382        Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3383      }
3384  }
3385
3386  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3387    if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3388      if ((SourceEnum->getDecl()->getIdentifier() ||
3389           SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3390          (TargetEnum->getDecl()->getIdentifier() ||
3391           TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3392          SourceEnum != TargetEnum) {
3393        if (isFromSystemMacro(S, CC))
3394          return;
3395
3396        return DiagnoseImpCast(S, E, SourceType, T, CC,
3397                               diag::warn_impcast_different_enum_types);
3398      }
3399
3400  return;
3401}
3402
3403void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3404
3405void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
3406                             SourceLocation CC, bool &ICContext) {
3407  E = E->IgnoreParenImpCasts();
3408
3409  if (isa<ConditionalOperator>(E))
3410    return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3411
3412  AnalyzeImplicitConversions(S, E, CC);
3413  if (E->getType() != T)
3414    return CheckImplicitConversion(S, E, T, CC, &ICContext);
3415  return;
3416}
3417
3418void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
3419  SourceLocation CC = E->getQuestionLoc();
3420
3421  AnalyzeImplicitConversions(S, E->getCond(), CC);
3422
3423  bool Suspicious = false;
3424  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3425  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
3426
3427  // If -Wconversion would have warned about either of the candidates
3428  // for a signedness conversion to the context type...
3429  if (!Suspicious) return;
3430
3431  // ...but it's currently ignored...
3432  if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3433                                 CC))
3434    return;
3435
3436  // ...then check whether it would have warned about either of the
3437  // candidates for a signedness conversion to the condition type.
3438  if (E->getType() == T) return;
3439
3440  Suspicious = false;
3441  CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3442                          E->getType(), CC, &Suspicious);
3443  if (!Suspicious)
3444    CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
3445                            E->getType(), CC, &Suspicious);
3446}
3447
3448/// AnalyzeImplicitConversions - Find and report any interesting
3449/// implicit conversions in the given expression.  There are a couple
3450/// of competing diagnostics here, -Wconversion and -Wsign-compare.
3451void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
3452  QualType T = OrigE->getType();
3453  Expr *E = OrigE->IgnoreParenImpCasts();
3454
3455  // For conditional operators, we analyze the arguments as if they
3456  // were being fed directly into the output.
3457  if (isa<ConditionalOperator>(E)) {
3458    ConditionalOperator *CO = cast<ConditionalOperator>(E);
3459    CheckConditionalOperator(S, CO, T);
3460    return;
3461  }
3462
3463  // Go ahead and check any implicit conversions we might have skipped.
3464  // The non-canonical typecheck is just an optimization;
3465  // CheckImplicitConversion will filter out dead implicit conversions.
3466  if (E->getType() != T)
3467    CheckImplicitConversion(S, E, T, CC);
3468
3469  // Now continue drilling into this expression.
3470
3471  // Skip past explicit casts.
3472  if (isa<ExplicitCastExpr>(E)) {
3473    E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
3474    return AnalyzeImplicitConversions(S, E, CC);
3475  }
3476
3477  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3478    // Do a somewhat different check with comparison operators.
3479    if (BO->isComparisonOp())
3480      return AnalyzeComparison(S, BO);
3481
3482    // And with assignments and compound assignments.
3483    if (BO->isAssignmentOp())
3484      return AnalyzeAssignment(S, BO);
3485  }
3486
3487  // These break the otherwise-useful invariant below.  Fortunately,
3488  // we don't really need to recurse into them, because any internal
3489  // expressions should have been analyzed already when they were
3490  // built into statements.
3491  if (isa<StmtExpr>(E)) return;
3492
3493  // Don't descend into unevaluated contexts.
3494  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
3495
3496  // Now just recurse over the expression's children.
3497  CC = E->getExprLoc();
3498  for (Stmt::child_range I = E->children(); I; ++I)
3499    AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
3500}
3501
3502} // end anonymous namespace
3503
3504/// Diagnoses "dangerous" implicit conversions within the given
3505/// expression (which is a full expression).  Implements -Wconversion
3506/// and -Wsign-compare.
3507///
3508/// \param CC the "context" location of the implicit conversion, i.e.
3509///   the most location of the syntactic entity requiring the implicit
3510///   conversion
3511void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
3512  // Don't diagnose in unevaluated contexts.
3513  if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3514    return;
3515
3516  // Don't diagnose for value- or type-dependent expressions.
3517  if (E->isTypeDependent() || E->isValueDependent())
3518    return;
3519
3520  // Check for array bounds violations in cases where the check isn't triggered
3521  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3522  // ArraySubscriptExpr is on the RHS of a variable initialization.
3523  CheckArrayAccess(E);
3524
3525  // This is not the right CC for (e.g.) a variable initialization.
3526  AnalyzeImplicitConversions(*this, E, CC);
3527}
3528
3529void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3530                                       FieldDecl *BitField,
3531                                       Expr *Init) {
3532  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3533}
3534
3535/// CheckParmsForFunctionDef - Check that the parameters of the given
3536/// function are appropriate for the definition of a function. This
3537/// takes care of any checks that cannot be performed on the
3538/// declaration itself, e.g., that the types of each of the function
3539/// parameters are complete.
3540bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3541                                    bool CheckParameterNames) {
3542  bool HasInvalidParm = false;
3543  for (; P != PEnd; ++P) {
3544    ParmVarDecl *Param = *P;
3545
3546    // C99 6.7.5.3p4: the parameters in a parameter type list in a
3547    // function declarator that is part of a function definition of
3548    // that function shall not have incomplete type.
3549    //
3550    // This is also C++ [dcl.fct]p6.
3551    if (!Param->isInvalidDecl() &&
3552        RequireCompleteType(Param->getLocation(), Param->getType(),
3553                               diag::err_typecheck_decl_incomplete_type)) {
3554      Param->setInvalidDecl();
3555      HasInvalidParm = true;
3556    }
3557
3558    // C99 6.9.1p5: If the declarator includes a parameter type list, the
3559    // declaration of each parameter shall include an identifier.
3560    if (CheckParameterNames &&
3561        Param->getIdentifier() == 0 &&
3562        !Param->isImplicit() &&
3563        !getLangOptions().CPlusPlus)
3564      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
3565
3566    // C99 6.7.5.3p12:
3567    //   If the function declarator is not part of a definition of that
3568    //   function, parameters may have incomplete type and may use the [*]
3569    //   notation in their sequences of declarator specifiers to specify
3570    //   variable length array types.
3571    QualType PType = Param->getOriginalType();
3572    if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3573      if (AT->getSizeModifier() == ArrayType::Star) {
3574        // FIXME: This diagnosic should point the the '[*]' if source-location
3575        // information is added for it.
3576        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3577      }
3578    }
3579  }
3580
3581  return HasInvalidParm;
3582}
3583
3584/// CheckCastAlign - Implements -Wcast-align, which warns when a
3585/// pointer cast increases the alignment requirements.
3586void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3587  // This is actually a lot of work to potentially be doing on every
3588  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3589  if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3590                                          TRange.getBegin())
3591        == Diagnostic::Ignored)
3592    return;
3593
3594  // Ignore dependent types.
3595  if (T->isDependentType() || Op->getType()->isDependentType())
3596    return;
3597
3598  // Require that the destination be a pointer type.
3599  const PointerType *DestPtr = T->getAs<PointerType>();
3600  if (!DestPtr) return;
3601
3602  // If the destination has alignment 1, we're done.
3603  QualType DestPointee = DestPtr->getPointeeType();
3604  if (DestPointee->isIncompleteType()) return;
3605  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3606  if (DestAlign.isOne()) return;
3607
3608  // Require that the source be a pointer type.
3609  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3610  if (!SrcPtr) return;
3611  QualType SrcPointee = SrcPtr->getPointeeType();
3612
3613  // Whitelist casts from cv void*.  We already implicitly
3614  // whitelisted casts to cv void*, since they have alignment 1.
3615  // Also whitelist casts involving incomplete types, which implicitly
3616  // includes 'void'.
3617  if (SrcPointee->isIncompleteType()) return;
3618
3619  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3620  if (SrcAlign >= DestAlign) return;
3621
3622  Diag(TRange.getBegin(), diag::warn_cast_align)
3623    << Op->getType() << T
3624    << static_cast<unsigned>(SrcAlign.getQuantity())
3625    << static_cast<unsigned>(DestAlign.getQuantity())
3626    << TRange << Op->getSourceRange();
3627}
3628
3629static const Type* getElementType(const Expr *BaseExpr) {
3630  const Type* EltType = BaseExpr->getType().getTypePtr();
3631  if (EltType->isAnyPointerType())
3632    return EltType->getPointeeType().getTypePtr();
3633  else if (EltType->isArrayType())
3634    return EltType->getBaseElementTypeUnsafe();
3635  return EltType;
3636}
3637
3638/// \brief Check whether this array fits the idiom of a size-one tail padded
3639/// array member of a struct.
3640///
3641/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3642/// commonly used to emulate flexible arrays in C89 code.
3643static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3644                                    const NamedDecl *ND) {
3645  if (Size != 1 || !ND) return false;
3646
3647  const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3648  if (!FD) return false;
3649
3650  // Don't consider sizes resulting from macro expansions or template argument
3651  // substitution to form C89 tail-padded arrays.
3652  ConstantArrayTypeLoc TL =
3653    cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3654  const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3655  if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3656    return false;
3657
3658  const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3659  if (!RD || !RD->isStruct())
3660    return false;
3661
3662  // See if this is the last field decl in the record.
3663  const Decl *D = FD;
3664  while ((D = D->getNextDeclInContext()))
3665    if (isa<FieldDecl>(D))
3666      return false;
3667  return true;
3668}
3669
3670void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3671                            bool isSubscript, bool AllowOnePastEnd) {
3672  const Type* EffectiveType = getElementType(BaseExpr);
3673  BaseExpr = BaseExpr->IgnoreParenCasts();
3674  IndexExpr = IndexExpr->IgnoreParenCasts();
3675
3676  const ConstantArrayType *ArrayTy =
3677    Context.getAsConstantArrayType(BaseExpr->getType());
3678  if (!ArrayTy)
3679    return;
3680
3681  if (IndexExpr->isValueDependent())
3682    return;
3683  llvm::APSInt index;
3684  if (!IndexExpr->isIntegerConstantExpr(index, Context))
3685    return;
3686
3687  const NamedDecl *ND = NULL;
3688  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3689    ND = dyn_cast<NamedDecl>(DRE->getDecl());
3690  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3691    ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3692
3693  if (index.isUnsigned() || !index.isNegative()) {
3694    llvm::APInt size = ArrayTy->getSize();
3695    if (!size.isStrictlyPositive())
3696      return;
3697
3698    const Type* BaseType = getElementType(BaseExpr);
3699    if (!isSubscript && BaseType != EffectiveType) {
3700      // Make sure we're comparing apples to apples when comparing index to size
3701      uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3702      uint64_t array_typesize = Context.getTypeSize(BaseType);
3703      // Handle ptrarith_typesize being zero, such as when casting to void*
3704      if (!ptrarith_typesize) ptrarith_typesize = 1;
3705      if (ptrarith_typesize != array_typesize) {
3706        // There's a cast to a different size type involved
3707        uint64_t ratio = array_typesize / ptrarith_typesize;
3708        // TODO: Be smarter about handling cases where array_typesize is not a
3709        // multiple of ptrarith_typesize
3710        if (ptrarith_typesize * ratio == array_typesize)
3711          size *= llvm::APInt(size.getBitWidth(), ratio);
3712      }
3713    }
3714
3715    if (size.getBitWidth() > index.getBitWidth())
3716      index = index.sext(size.getBitWidth());
3717    else if (size.getBitWidth() < index.getBitWidth())
3718      size = size.sext(index.getBitWidth());
3719
3720    // For array subscripting the index must be less than size, but for pointer
3721    // arithmetic also allow the index (offset) to be equal to size since
3722    // computing the next address after the end of the array is legal and
3723    // commonly done e.g. in C++ iterators and range-based for loops.
3724    if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
3725      return;
3726
3727    // Also don't warn for arrays of size 1 which are members of some
3728    // structure. These are often used to approximate flexible arrays in C89
3729    // code.
3730    if (IsTailPaddedMemberArray(*this, size, ND))
3731      return;
3732
3733    unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3734    if (isSubscript)
3735      DiagID = diag::warn_array_index_exceeds_bounds;
3736
3737    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3738                        PDiag(DiagID) << index.toString(10, true)
3739                          << size.toString(10, true)
3740                          << (unsigned)size.getLimitedValue(~0U)
3741                          << IndexExpr->getSourceRange());
3742  } else {
3743    unsigned DiagID = diag::warn_array_index_precedes_bounds;
3744    if (!isSubscript) {
3745      DiagID = diag::warn_ptr_arith_precedes_bounds;
3746      if (index.isNegative()) index = -index;
3747    }
3748
3749    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3750                        PDiag(DiagID) << index.toString(10, true)
3751                          << IndexExpr->getSourceRange());
3752  }
3753
3754  if (ND)
3755    DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3756                        PDiag(diag::note_array_index_out_of_bounds)
3757                          << ND->getDeclName());
3758}
3759
3760void Sema::CheckArrayAccess(const Expr *expr) {
3761  int AllowOnePastEnd = 0;
3762  while (expr) {
3763    expr = expr->IgnoreParenImpCasts();
3764    switch (expr->getStmtClass()) {
3765      case Stmt::ArraySubscriptExprClass: {
3766        const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
3767        CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
3768                         AllowOnePastEnd > 0);
3769        return;
3770      }
3771      case Stmt::UnaryOperatorClass: {
3772        // Only unwrap the * and & unary operators
3773        const UnaryOperator *UO = cast<UnaryOperator>(expr);
3774        expr = UO->getSubExpr();
3775        switch (UO->getOpcode()) {
3776          case UO_AddrOf:
3777            AllowOnePastEnd++;
3778            break;
3779          case UO_Deref:
3780            AllowOnePastEnd--;
3781            break;
3782          default:
3783            return;
3784        }
3785        break;
3786      }
3787      case Stmt::ConditionalOperatorClass: {
3788        const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3789        if (const Expr *lhs = cond->getLHS())
3790          CheckArrayAccess(lhs);
3791        if (const Expr *rhs = cond->getRHS())
3792          CheckArrayAccess(rhs);
3793        return;
3794      }
3795      default:
3796        return;
3797    }
3798  }
3799}
3800
3801//===--- CHECK: Objective-C retain cycles ----------------------------------//
3802
3803namespace {
3804  struct RetainCycleOwner {
3805    RetainCycleOwner() : Variable(0), Indirect(false) {}
3806    VarDecl *Variable;
3807    SourceRange Range;
3808    SourceLocation Loc;
3809    bool Indirect;
3810
3811    void setLocsFrom(Expr *e) {
3812      Loc = e->getExprLoc();
3813      Range = e->getSourceRange();
3814    }
3815  };
3816}
3817
3818/// Consider whether capturing the given variable can possibly lead to
3819/// a retain cycle.
3820static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
3821  // In ARC, it's captured strongly iff the variable has __strong
3822  // lifetime.  In MRR, it's captured strongly if the variable is
3823  // __block and has an appropriate type.
3824  if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3825    return false;
3826
3827  owner.Variable = var;
3828  owner.setLocsFrom(ref);
3829  return true;
3830}
3831
3832static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
3833  while (true) {
3834    e = e->IgnoreParens();
3835    if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
3836      switch (cast->getCastKind()) {
3837      case CK_BitCast:
3838      case CK_LValueBitCast:
3839      case CK_LValueToRValue:
3840      case CK_ObjCReclaimReturnedObject:
3841        e = cast->getSubExpr();
3842        continue;
3843
3844      case CK_GetObjCProperty: {
3845        // Bail out if this isn't a strong explicit property.
3846        const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
3847        if (pre->isImplicitProperty()) return false;
3848        ObjCPropertyDecl *property = pre->getExplicitProperty();
3849        if (!(property->getPropertyAttributes() &
3850              (ObjCPropertyDecl::OBJC_PR_retain |
3851               ObjCPropertyDecl::OBJC_PR_copy |
3852               ObjCPropertyDecl::OBJC_PR_strong)) &&
3853            !(property->getPropertyIvarDecl() &&
3854              property->getPropertyIvarDecl()->getType()
3855                .getObjCLifetime() == Qualifiers::OCL_Strong))
3856          return false;
3857
3858        owner.Indirect = true;
3859        e = const_cast<Expr*>(pre->getBase());
3860        continue;
3861      }
3862
3863      default:
3864        return false;
3865      }
3866    }
3867
3868    if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
3869      ObjCIvarDecl *ivar = ref->getDecl();
3870      if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3871        return false;
3872
3873      // Try to find a retain cycle in the base.
3874      if (!findRetainCycleOwner(ref->getBase(), owner))
3875        return false;
3876
3877      if (ref->isFreeIvar()) owner.setLocsFrom(ref);
3878      owner.Indirect = true;
3879      return true;
3880    }
3881
3882    if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
3883      VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
3884      if (!var) return false;
3885      return considerVariable(var, ref, owner);
3886    }
3887
3888    if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
3889      owner.Variable = ref->getDecl();
3890      owner.setLocsFrom(ref);
3891      return true;
3892    }
3893
3894    if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
3895      if (member->isArrow()) return false;
3896
3897      // Don't count this as an indirect ownership.
3898      e = member->getBase();
3899      continue;
3900    }
3901
3902    // Array ivars?
3903
3904    return false;
3905  }
3906}
3907
3908namespace {
3909  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
3910    FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
3911      : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
3912        Variable(variable), Capturer(0) {}
3913
3914    VarDecl *Variable;
3915    Expr *Capturer;
3916
3917    void VisitDeclRefExpr(DeclRefExpr *ref) {
3918      if (ref->getDecl() == Variable && !Capturer)
3919        Capturer = ref;
3920    }
3921
3922    void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
3923      if (ref->getDecl() == Variable && !Capturer)
3924        Capturer = ref;
3925    }
3926
3927    void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
3928      if (Capturer) return;
3929      Visit(ref->getBase());
3930      if (Capturer && ref->isFreeIvar())
3931        Capturer = ref;
3932    }
3933
3934    void VisitBlockExpr(BlockExpr *block) {
3935      // Look inside nested blocks
3936      if (block->getBlockDecl()->capturesVariable(Variable))
3937        Visit(block->getBlockDecl()->getBody());
3938    }
3939  };
3940}
3941
3942/// Check whether the given argument is a block which captures a
3943/// variable.
3944static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
3945  assert(owner.Variable && owner.Loc.isValid());
3946
3947  e = e->IgnoreParenCasts();
3948  BlockExpr *block = dyn_cast<BlockExpr>(e);
3949  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
3950    return 0;
3951
3952  FindCaptureVisitor visitor(S.Context, owner.Variable);
3953  visitor.Visit(block->getBlockDecl()->getBody());
3954  return visitor.Capturer;
3955}
3956
3957static void diagnoseRetainCycle(Sema &S, Expr *capturer,
3958                                RetainCycleOwner &owner) {
3959  assert(capturer);
3960  assert(owner.Variable && owner.Loc.isValid());
3961
3962  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
3963    << owner.Variable << capturer->getSourceRange();
3964  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
3965    << owner.Indirect << owner.Range;
3966}
3967
3968/// Check for a keyword selector that starts with the word 'add' or
3969/// 'set'.
3970static bool isSetterLikeSelector(Selector sel) {
3971  if (sel.isUnarySelector()) return false;
3972
3973  StringRef str = sel.getNameForSlot(0);
3974  while (!str.empty() && str.front() == '_') str = str.substr(1);
3975  if (str.startswith("set") || str.startswith("add"))
3976    str = str.substr(3);
3977  else
3978    return false;
3979
3980  if (str.empty()) return true;
3981  return !islower(str.front());
3982}
3983
3984/// Check a message send to see if it's likely to cause a retain cycle.
3985void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
3986  // Only check instance methods whose selector looks like a setter.
3987  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
3988    return;
3989
3990  // Try to find a variable that the receiver is strongly owned by.
3991  RetainCycleOwner owner;
3992  if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
3993    if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
3994      return;
3995  } else {
3996    assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
3997    owner.Variable = getCurMethodDecl()->getSelfDecl();
3998    owner.Loc = msg->getSuperLoc();
3999    owner.Range = msg->getSuperLoc();
4000  }
4001
4002  // Check whether the receiver is captured by any of the arguments.
4003  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4004    if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4005      return diagnoseRetainCycle(*this, capturer, owner);
4006}
4007
4008/// Check a property assign to see if it's likely to cause a retain cycle.
4009void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4010  RetainCycleOwner owner;
4011  if (!findRetainCycleOwner(receiver, owner))
4012    return;
4013
4014  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4015    diagnoseRetainCycle(*this, capturer, owner);
4016}
4017
4018bool Sema::checkUnsafeAssigns(SourceLocation Loc,
4019                              QualType LHS, Expr *RHS) {
4020  Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4021  if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
4022    return false;
4023  // strip off any implicit cast added to get to the one arc-specific
4024  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4025    if (cast->getCastKind() == CK_ObjCConsumeObject) {
4026      Diag(Loc, diag::warn_arc_retained_assign)
4027        << (LT == Qualifiers::OCL_ExplicitNone)
4028        << RHS->getSourceRange();
4029      return true;
4030    }
4031    RHS = cast->getSubExpr();
4032  }
4033  return false;
4034}
4035
4036void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4037                              Expr *LHS, Expr *RHS) {
4038  QualType LHSType = LHS->getType();
4039  if (checkUnsafeAssigns(Loc, LHSType, RHS))
4040    return;
4041  Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4042  // FIXME. Check for other life times.
4043  if (LT != Qualifiers::OCL_None)
4044    return;
4045
4046  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4047    if (PRE->isImplicitProperty())
4048      return;
4049    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4050    if (!PD)
4051      return;
4052
4053    unsigned Attributes = PD->getPropertyAttributes();
4054    if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4055      while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4056        if (cast->getCastKind() == CK_ObjCConsumeObject) {
4057          Diag(Loc, diag::warn_arc_retained_property_assign)
4058          << RHS->getSourceRange();
4059          return;
4060        }
4061        RHS = cast->getSubExpr();
4062      }
4063  }
4064}
4065