SemaChecking.cpp revision 263508
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/SemaInternal.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/Analysis/Analyses/FormatString.h"
27#include "clang/Basic/CharInfo.h"
28#include "clang/Basic/TargetBuiltins.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "llvm/ADT/SmallBitVector.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/Support/ConvertUTF.h"
39#include "llvm/Support/raw_ostream.h"
40#include <limits>
41using namespace clang;
42using namespace sema;
43
44SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45                                                    unsigned ByteNo) const {
46  return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
47                               PP.getLangOpts(), PP.getTargetInfo());
48}
49
50/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking.  Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53  unsigned argCount = call->getNumArgs();
54  if (argCount == desiredArgCount) return false;
55
56  if (argCount < desiredArgCount)
57    return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58        << 0 /*function call*/ << desiredArgCount << argCount
59        << call->getSourceRange();
60
61  // Highlight all the excess arguments.
62  SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63                    call->getArg(argCount - 1)->getLocEnd());
64
65  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66    << 0 /*function call*/ << desiredArgCount << argCount
67    << call->getArg(1)->getSourceRange();
68}
69
70/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73  if (checkArgCount(S, TheCall, 2))
74    return true;
75
76  // First argument should be an integer.
77  Expr *ValArg = TheCall->getArg(0);
78  QualType Ty = ValArg->getType();
79  if (!Ty->isIntegerType()) {
80    S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81      << ValArg->getSourceRange();
82    return true;
83  }
84
85  // Second argument should be a constant string.
86  Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87  StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88  if (!Literal || !Literal->isAscii()) {
89    S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90      << StrArg->getSourceRange();
91    return true;
92  }
93
94  TheCall->setType(Ty);
95  return false;
96}
97
98/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101  if (checkArgCount(S, TheCall, 1))
102    return true;
103
104  ExprResult Arg(S.Owned(TheCall->getArg(0)));
105  QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106  if (ResultType.isNull())
107    return true;
108
109  TheCall->setArg(0, Arg.take());
110  TheCall->setType(ResultType);
111  return false;
112}
113
114ExprResult
115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
116  ExprResult TheCallResult(Owned(TheCall));
117
118  // Find out if any arguments are required to be integer constant expressions.
119  unsigned ICEArguments = 0;
120  ASTContext::GetBuiltinTypeError Error;
121  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122  if (Error != ASTContext::GE_None)
123    ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
124
125  // If any arguments are required to be ICE's, check and diagnose.
126  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127    // Skip arguments not required to be ICE's.
128    if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130    llvm::APSInt Result;
131    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132      return true;
133    ICEArguments &= ~(1 << ArgNo);
134  }
135
136  switch (BuiltinID) {
137  case Builtin::BI__builtin___CFStringMakeConstantString:
138    assert(TheCall->getNumArgs() == 1 &&
139           "Wrong # arguments to builtin CFStringMakeConstantString");
140    if (CheckObjCString(TheCall->getArg(0)))
141      return ExprError();
142    break;
143  case Builtin::BI__builtin_stdarg_start:
144  case Builtin::BI__builtin_va_start:
145    if (SemaBuiltinVAStart(TheCall))
146      return ExprError();
147    break;
148  case Builtin::BI__builtin_isgreater:
149  case Builtin::BI__builtin_isgreaterequal:
150  case Builtin::BI__builtin_isless:
151  case Builtin::BI__builtin_islessequal:
152  case Builtin::BI__builtin_islessgreater:
153  case Builtin::BI__builtin_isunordered:
154    if (SemaBuiltinUnorderedCompare(TheCall))
155      return ExprError();
156    break;
157  case Builtin::BI__builtin_fpclassify:
158    if (SemaBuiltinFPClassification(TheCall, 6))
159      return ExprError();
160    break;
161  case Builtin::BI__builtin_isfinite:
162  case Builtin::BI__builtin_isinf:
163  case Builtin::BI__builtin_isinf_sign:
164  case Builtin::BI__builtin_isnan:
165  case Builtin::BI__builtin_isnormal:
166    if (SemaBuiltinFPClassification(TheCall, 1))
167      return ExprError();
168    break;
169  case Builtin::BI__builtin_shufflevector:
170    return SemaBuiltinShuffleVector(TheCall);
171    // TheCall will be freed by the smart pointer here, but that's fine, since
172    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
173  case Builtin::BI__builtin_prefetch:
174    if (SemaBuiltinPrefetch(TheCall))
175      return ExprError();
176    break;
177  case Builtin::BI__builtin_object_size:
178    if (SemaBuiltinObjectSize(TheCall))
179      return ExprError();
180    break;
181  case Builtin::BI__builtin_longjmp:
182    if (SemaBuiltinLongjmp(TheCall))
183      return ExprError();
184    break;
185
186  case Builtin::BI__builtin_classify_type:
187    if (checkArgCount(*this, TheCall, 1)) return true;
188    TheCall->setType(Context.IntTy);
189    break;
190  case Builtin::BI__builtin_constant_p:
191    if (checkArgCount(*this, TheCall, 1)) return true;
192    TheCall->setType(Context.IntTy);
193    break;
194  case Builtin::BI__sync_fetch_and_add:
195  case Builtin::BI__sync_fetch_and_add_1:
196  case Builtin::BI__sync_fetch_and_add_2:
197  case Builtin::BI__sync_fetch_and_add_4:
198  case Builtin::BI__sync_fetch_and_add_8:
199  case Builtin::BI__sync_fetch_and_add_16:
200  case Builtin::BI__sync_fetch_and_sub:
201  case Builtin::BI__sync_fetch_and_sub_1:
202  case Builtin::BI__sync_fetch_and_sub_2:
203  case Builtin::BI__sync_fetch_and_sub_4:
204  case Builtin::BI__sync_fetch_and_sub_8:
205  case Builtin::BI__sync_fetch_and_sub_16:
206  case Builtin::BI__sync_fetch_and_or:
207  case Builtin::BI__sync_fetch_and_or_1:
208  case Builtin::BI__sync_fetch_and_or_2:
209  case Builtin::BI__sync_fetch_and_or_4:
210  case Builtin::BI__sync_fetch_and_or_8:
211  case Builtin::BI__sync_fetch_and_or_16:
212  case Builtin::BI__sync_fetch_and_and:
213  case Builtin::BI__sync_fetch_and_and_1:
214  case Builtin::BI__sync_fetch_and_and_2:
215  case Builtin::BI__sync_fetch_and_and_4:
216  case Builtin::BI__sync_fetch_and_and_8:
217  case Builtin::BI__sync_fetch_and_and_16:
218  case Builtin::BI__sync_fetch_and_xor:
219  case Builtin::BI__sync_fetch_and_xor_1:
220  case Builtin::BI__sync_fetch_and_xor_2:
221  case Builtin::BI__sync_fetch_and_xor_4:
222  case Builtin::BI__sync_fetch_and_xor_8:
223  case Builtin::BI__sync_fetch_and_xor_16:
224  case Builtin::BI__sync_add_and_fetch:
225  case Builtin::BI__sync_add_and_fetch_1:
226  case Builtin::BI__sync_add_and_fetch_2:
227  case Builtin::BI__sync_add_and_fetch_4:
228  case Builtin::BI__sync_add_and_fetch_8:
229  case Builtin::BI__sync_add_and_fetch_16:
230  case Builtin::BI__sync_sub_and_fetch:
231  case Builtin::BI__sync_sub_and_fetch_1:
232  case Builtin::BI__sync_sub_and_fetch_2:
233  case Builtin::BI__sync_sub_and_fetch_4:
234  case Builtin::BI__sync_sub_and_fetch_8:
235  case Builtin::BI__sync_sub_and_fetch_16:
236  case Builtin::BI__sync_and_and_fetch:
237  case Builtin::BI__sync_and_and_fetch_1:
238  case Builtin::BI__sync_and_and_fetch_2:
239  case Builtin::BI__sync_and_and_fetch_4:
240  case Builtin::BI__sync_and_and_fetch_8:
241  case Builtin::BI__sync_and_and_fetch_16:
242  case Builtin::BI__sync_or_and_fetch:
243  case Builtin::BI__sync_or_and_fetch_1:
244  case Builtin::BI__sync_or_and_fetch_2:
245  case Builtin::BI__sync_or_and_fetch_4:
246  case Builtin::BI__sync_or_and_fetch_8:
247  case Builtin::BI__sync_or_and_fetch_16:
248  case Builtin::BI__sync_xor_and_fetch:
249  case Builtin::BI__sync_xor_and_fetch_1:
250  case Builtin::BI__sync_xor_and_fetch_2:
251  case Builtin::BI__sync_xor_and_fetch_4:
252  case Builtin::BI__sync_xor_and_fetch_8:
253  case Builtin::BI__sync_xor_and_fetch_16:
254  case Builtin::BI__sync_val_compare_and_swap:
255  case Builtin::BI__sync_val_compare_and_swap_1:
256  case Builtin::BI__sync_val_compare_and_swap_2:
257  case Builtin::BI__sync_val_compare_and_swap_4:
258  case Builtin::BI__sync_val_compare_and_swap_8:
259  case Builtin::BI__sync_val_compare_and_swap_16:
260  case Builtin::BI__sync_bool_compare_and_swap:
261  case Builtin::BI__sync_bool_compare_and_swap_1:
262  case Builtin::BI__sync_bool_compare_and_swap_2:
263  case Builtin::BI__sync_bool_compare_and_swap_4:
264  case Builtin::BI__sync_bool_compare_and_swap_8:
265  case Builtin::BI__sync_bool_compare_and_swap_16:
266  case Builtin::BI__sync_lock_test_and_set:
267  case Builtin::BI__sync_lock_test_and_set_1:
268  case Builtin::BI__sync_lock_test_and_set_2:
269  case Builtin::BI__sync_lock_test_and_set_4:
270  case Builtin::BI__sync_lock_test_and_set_8:
271  case Builtin::BI__sync_lock_test_and_set_16:
272  case Builtin::BI__sync_lock_release:
273  case Builtin::BI__sync_lock_release_1:
274  case Builtin::BI__sync_lock_release_2:
275  case Builtin::BI__sync_lock_release_4:
276  case Builtin::BI__sync_lock_release_8:
277  case Builtin::BI__sync_lock_release_16:
278  case Builtin::BI__sync_swap:
279  case Builtin::BI__sync_swap_1:
280  case Builtin::BI__sync_swap_2:
281  case Builtin::BI__sync_swap_4:
282  case Builtin::BI__sync_swap_8:
283  case Builtin::BI__sync_swap_16:
284    return SemaBuiltinAtomicOverloaded(TheCallResult);
285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287  case Builtin::BI##ID: \
288    return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
289#include "clang/Basic/Builtins.def"
290  case Builtin::BI__builtin_annotation:
291    if (SemaBuiltinAnnotation(*this, TheCall))
292      return ExprError();
293    break;
294  case Builtin::BI__builtin_addressof:
295    if (SemaBuiltinAddressof(*this, TheCall))
296      return ExprError();
297    break;
298  }
299
300  // Since the target specific builtins for each arch overlap, only check those
301  // of the arch we are compiling for.
302  if (BuiltinID >= Builtin::FirstTSBuiltin) {
303    switch (Context.getTargetInfo().getTriple().getArch()) {
304      case llvm::Triple::arm:
305      case llvm::Triple::thumb:
306        if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307          return ExprError();
308        break;
309      case llvm::Triple::aarch64:
310        if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311          return ExprError();
312        break;
313      case llvm::Triple::mips:
314      case llvm::Triple::mipsel:
315      case llvm::Triple::mips64:
316      case llvm::Triple::mips64el:
317        if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318          return ExprError();
319        break;
320      default:
321        break;
322    }
323  }
324
325  return TheCallResult;
326}
327
328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
330  NeonTypeFlags Type(t);
331  int IsQuad = Type.isQuad();
332  switch (Type.getEltType()) {
333  case NeonTypeFlags::Int8:
334  case NeonTypeFlags::Poly8:
335    return shift ? 7 : (8 << IsQuad) - 1;
336  case NeonTypeFlags::Int16:
337  case NeonTypeFlags::Poly16:
338    return shift ? 15 : (4 << IsQuad) - 1;
339  case NeonTypeFlags::Int32:
340    return shift ? 31 : (2 << IsQuad) - 1;
341  case NeonTypeFlags::Int64:
342  case NeonTypeFlags::Poly64:
343    return shift ? 63 : (1 << IsQuad) - 1;
344  case NeonTypeFlags::Float16:
345    assert(!shift && "cannot shift float types!");
346    return (4 << IsQuad) - 1;
347  case NeonTypeFlags::Float32:
348    assert(!shift && "cannot shift float types!");
349    return (2 << IsQuad) - 1;
350  case NeonTypeFlags::Float64:
351    assert(!shift && "cannot shift float types!");
352    return (1 << IsQuad) - 1;
353  }
354  llvm_unreachable("Invalid NeonTypeFlag!");
355}
356
357/// getNeonEltType - Return the QualType corresponding to the elements of
358/// the vector type specified by the NeonTypeFlags.  This is used to check
359/// the pointer arguments for Neon load/store intrinsics.
360static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
361                               bool IsAArch64) {
362  switch (Flags.getEltType()) {
363  case NeonTypeFlags::Int8:
364    return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
365  case NeonTypeFlags::Int16:
366    return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
367  case NeonTypeFlags::Int32:
368    return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
369  case NeonTypeFlags::Int64:
370    return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
371  case NeonTypeFlags::Poly8:
372    return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
373  case NeonTypeFlags::Poly16:
374    return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
375  case NeonTypeFlags::Poly64:
376    return Context.UnsignedLongLongTy;
377  case NeonTypeFlags::Float16:
378    return Context.HalfTy;
379  case NeonTypeFlags::Float32:
380    return Context.FloatTy;
381  case NeonTypeFlags::Float64:
382    return Context.DoubleTy;
383  }
384  llvm_unreachable("Invalid NeonTypeFlag!");
385}
386
387bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
388                                           CallExpr *TheCall) {
389
390  llvm::APSInt Result;
391
392  uint64_t mask = 0;
393  unsigned TV = 0;
394  int PtrArgNum = -1;
395  bool HasConstPtr = false;
396  switch (BuiltinID) {
397#define GET_NEON_AARCH64_OVERLOAD_CHECK
398#include "clang/Basic/arm_neon.inc"
399#undef GET_NEON_AARCH64_OVERLOAD_CHECK
400  }
401
402  // For NEON intrinsics which are overloaded on vector element type, validate
403  // the immediate which specifies which variant to emit.
404  unsigned ImmArg = TheCall->getNumArgs() - 1;
405  if (mask) {
406    if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
407      return true;
408
409    TV = Result.getLimitedValue(64);
410    if ((TV > 63) || (mask & (1ULL << TV)) == 0)
411      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
412             << TheCall->getArg(ImmArg)->getSourceRange();
413  }
414
415  if (PtrArgNum >= 0) {
416    // Check that pointer arguments have the specified type.
417    Expr *Arg = TheCall->getArg(PtrArgNum);
418    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
419      Arg = ICE->getSubExpr();
420    ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
421    QualType RHSTy = RHS.get()->getType();
422    QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, true);
423    if (HasConstPtr)
424      EltTy = EltTy.withConst();
425    QualType LHSTy = Context.getPointerType(EltTy);
426    AssignConvertType ConvTy;
427    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
428    if (RHS.isInvalid())
429      return true;
430    if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
431                                 RHS.get(), AA_Assigning))
432      return true;
433  }
434
435  // For NEON intrinsics which take an immediate value as part of the
436  // instruction, range check them here.
437  unsigned i = 0, l = 0, u = 0;
438  switch (BuiltinID) {
439  default:
440    return false;
441#define GET_NEON_AARCH64_IMMEDIATE_CHECK
442#include "clang/Basic/arm_neon.inc"
443#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
444  }
445  ;
446
447  // We can't check the value of a dependent argument.
448  if (TheCall->getArg(i)->isTypeDependent() ||
449      TheCall->getArg(i)->isValueDependent())
450    return false;
451
452  // Check that the immediate argument is actually a constant.
453  if (SemaBuiltinConstantArg(TheCall, i, Result))
454    return true;
455
456  // Range check against the upper/lower values for this isntruction.
457  unsigned Val = Result.getZExtValue();
458  if (Val < l || Val > (u + l))
459    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
460           << l << u + l << TheCall->getArg(i)->getSourceRange();
461
462  return false;
463}
464
465bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
466  assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
467          BuiltinID == ARM::BI__builtin_arm_strex) &&
468         "unexpected ARM builtin");
469  bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
470
471  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
472
473  // Ensure that we have the proper number of arguments.
474  if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
475    return true;
476
477  // Inspect the pointer argument of the atomic builtin.  This should always be
478  // a pointer type, whose element is an integral scalar or pointer type.
479  // Because it is a pointer type, we don't have to worry about any implicit
480  // casts here.
481  Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
482  ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
483  if (PointerArgRes.isInvalid())
484    return true;
485  PointerArg = PointerArgRes.take();
486
487  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
488  if (!pointerType) {
489    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
490      << PointerArg->getType() << PointerArg->getSourceRange();
491    return true;
492  }
493
494  // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
495  // task is to insert the appropriate casts into the AST. First work out just
496  // what the appropriate type is.
497  QualType ValType = pointerType->getPointeeType();
498  QualType AddrType = ValType.getUnqualifiedType().withVolatile();
499  if (IsLdrex)
500    AddrType.addConst();
501
502  // Issue a warning if the cast is dodgy.
503  CastKind CastNeeded = CK_NoOp;
504  if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
505    CastNeeded = CK_BitCast;
506    Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
507      << PointerArg->getType()
508      << Context.getPointerType(AddrType)
509      << AA_Passing << PointerArg->getSourceRange();
510  }
511
512  // Finally, do the cast and replace the argument with the corrected version.
513  AddrType = Context.getPointerType(AddrType);
514  PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
515  if (PointerArgRes.isInvalid())
516    return true;
517  PointerArg = PointerArgRes.take();
518
519  TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
520
521  // In general, we allow ints, floats and pointers to be loaded and stored.
522  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
523      !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
524    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
525      << PointerArg->getType() << PointerArg->getSourceRange();
526    return true;
527  }
528
529  // But ARM doesn't have instructions to deal with 128-bit versions.
530  if (Context.getTypeSize(ValType) > 64) {
531    Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
532      << PointerArg->getType() << PointerArg->getSourceRange();
533    return true;
534  }
535
536  switch (ValType.getObjCLifetime()) {
537  case Qualifiers::OCL_None:
538  case Qualifiers::OCL_ExplicitNone:
539    // okay
540    break;
541
542  case Qualifiers::OCL_Weak:
543  case Qualifiers::OCL_Strong:
544  case Qualifiers::OCL_Autoreleasing:
545    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
546      << ValType << PointerArg->getSourceRange();
547    return true;
548  }
549
550
551  if (IsLdrex) {
552    TheCall->setType(ValType);
553    return false;
554  }
555
556  // Initialize the argument to be stored.
557  ExprResult ValArg = TheCall->getArg(0);
558  InitializedEntity Entity = InitializedEntity::InitializeParameter(
559      Context, ValType, /*consume*/ false);
560  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
561  if (ValArg.isInvalid())
562    return true;
563  TheCall->setArg(0, ValArg.get());
564
565  // __builtin_arm_strex always returns an int. It's marked as such in the .def,
566  // but the custom checker bypasses all default analysis.
567  TheCall->setType(Context.IntTy);
568  return false;
569}
570
571bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
572  llvm::APSInt Result;
573
574  if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
575      BuiltinID == ARM::BI__builtin_arm_strex) {
576    return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
577  }
578
579  uint64_t mask = 0;
580  unsigned TV = 0;
581  int PtrArgNum = -1;
582  bool HasConstPtr = false;
583  switch (BuiltinID) {
584#define GET_NEON_OVERLOAD_CHECK
585#include "clang/Basic/arm_neon.inc"
586#undef GET_NEON_OVERLOAD_CHECK
587  }
588
589  // For NEON intrinsics which are overloaded on vector element type, validate
590  // the immediate which specifies which variant to emit.
591  unsigned ImmArg = TheCall->getNumArgs()-1;
592  if (mask) {
593    if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
594      return true;
595
596    TV = Result.getLimitedValue(64);
597    if ((TV > 63) || (mask & (1ULL << TV)) == 0)
598      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
599        << TheCall->getArg(ImmArg)->getSourceRange();
600  }
601
602  if (PtrArgNum >= 0) {
603    // Check that pointer arguments have the specified type.
604    Expr *Arg = TheCall->getArg(PtrArgNum);
605    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
606      Arg = ICE->getSubExpr();
607    ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
608    QualType RHSTy = RHS.get()->getType();
609    QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, false);
610    if (HasConstPtr)
611      EltTy = EltTy.withConst();
612    QualType LHSTy = Context.getPointerType(EltTy);
613    AssignConvertType ConvTy;
614    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
615    if (RHS.isInvalid())
616      return true;
617    if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
618                                 RHS.get(), AA_Assigning))
619      return true;
620  }
621
622  // For NEON intrinsics which take an immediate value as part of the
623  // instruction, range check them here.
624  unsigned i = 0, l = 0, u = 0;
625  switch (BuiltinID) {
626  default: return false;
627  case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
628  case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
629  case ARM::BI__builtin_arm_vcvtr_f:
630  case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
631  case ARM::BI__builtin_arm_dmb:
632  case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
633#define GET_NEON_IMMEDIATE_CHECK
634#include "clang/Basic/arm_neon.inc"
635#undef GET_NEON_IMMEDIATE_CHECK
636  };
637
638  // We can't check the value of a dependent argument.
639  if (TheCall->getArg(i)->isTypeDependent() ||
640      TheCall->getArg(i)->isValueDependent())
641    return false;
642
643  // Check that the immediate argument is actually a constant.
644  if (SemaBuiltinConstantArg(TheCall, i, Result))
645    return true;
646
647  // Range check against the upper/lower values for this isntruction.
648  unsigned Val = Result.getZExtValue();
649  if (Val < l || Val > (u + l))
650    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
651      << l << u+l << TheCall->getArg(i)->getSourceRange();
652
653  // FIXME: VFP Intrinsics should error if VFP not present.
654  return false;
655}
656
657bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
658  unsigned i = 0, l = 0, u = 0;
659  switch (BuiltinID) {
660  default: return false;
661  case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
662  case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
663  case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
664  case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
665  case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
666  case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
667  case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
668  };
669
670  // We can't check the value of a dependent argument.
671  if (TheCall->getArg(i)->isTypeDependent() ||
672      TheCall->getArg(i)->isValueDependent())
673    return false;
674
675  // Check that the immediate argument is actually a constant.
676  llvm::APSInt Result;
677  if (SemaBuiltinConstantArg(TheCall, i, Result))
678    return true;
679
680  // Range check against the upper/lower values for this instruction.
681  unsigned Val = Result.getZExtValue();
682  if (Val < l || Val > u)
683    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
684      << l << u << TheCall->getArg(i)->getSourceRange();
685
686  return false;
687}
688
689/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
690/// parameter with the FormatAttr's correct format_idx and firstDataArg.
691/// Returns true when the format fits the function and the FormatStringInfo has
692/// been populated.
693bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
694                               FormatStringInfo *FSI) {
695  FSI->HasVAListArg = Format->getFirstArg() == 0;
696  FSI->FormatIdx = Format->getFormatIdx() - 1;
697  FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
698
699  // The way the format attribute works in GCC, the implicit this argument
700  // of member functions is counted. However, it doesn't appear in our own
701  // lists, so decrement format_idx in that case.
702  if (IsCXXMember) {
703    if(FSI->FormatIdx == 0)
704      return false;
705    --FSI->FormatIdx;
706    if (FSI->FirstDataArg != 0)
707      --FSI->FirstDataArg;
708  }
709  return true;
710}
711
712/// Handles the checks for format strings, non-POD arguments to vararg
713/// functions, and NULL arguments passed to non-NULL parameters.
714void Sema::checkCall(NamedDecl *FDecl,
715                     ArrayRef<const Expr *> Args,
716                     unsigned NumProtoArgs,
717                     bool IsMemberFunction,
718                     SourceLocation Loc,
719                     SourceRange Range,
720                     VariadicCallType CallType) {
721  // FIXME: We should check as much as we can in the template definition.
722  if (CurContext->isDependentContext())
723    return;
724
725  // Printf and scanf checking.
726  llvm::SmallBitVector CheckedVarArgs;
727  if (FDecl) {
728    for (specific_attr_iterator<FormatAttr>
729             I = FDecl->specific_attr_begin<FormatAttr>(),
730             E = FDecl->specific_attr_end<FormatAttr>();
731         I != E; ++I) {
732      // Only create vector if there are format attributes.
733      CheckedVarArgs.resize(Args.size());
734
735      CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
736                           CheckedVarArgs);
737    }
738  }
739
740  // Refuse POD arguments that weren't caught by the format string
741  // checks above.
742  if (CallType != VariadicDoesNotApply) {
743    for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
744      // Args[ArgIdx] can be null in malformed code.
745      if (const Expr *Arg = Args[ArgIdx]) {
746        if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
747          checkVariadicArgument(Arg, CallType);
748      }
749    }
750  }
751
752  if (FDecl) {
753    for (specific_attr_iterator<NonNullAttr>
754           I = FDecl->specific_attr_begin<NonNullAttr>(),
755           E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
756      CheckNonNullArguments(*I, Args.data(), Loc);
757
758    // Type safety checking.
759    for (specific_attr_iterator<ArgumentWithTypeTagAttr>
760           i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
761           e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
762         i != e; ++i) {
763      CheckArgumentWithTypeTag(*i, Args.data());
764    }
765  }
766}
767
768/// CheckConstructorCall - Check a constructor call for correctness and safety
769/// properties not enforced by the C type system.
770void Sema::CheckConstructorCall(FunctionDecl *FDecl,
771                                ArrayRef<const Expr *> Args,
772                                const FunctionProtoType *Proto,
773                                SourceLocation Loc) {
774  VariadicCallType CallType =
775    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
776  checkCall(FDecl, Args, Proto->getNumArgs(),
777            /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
778}
779
780/// CheckFunctionCall - Check a direct function call for various correctness
781/// and safety properties not strictly enforced by the C type system.
782bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
783                             const FunctionProtoType *Proto) {
784  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
785                              isa<CXXMethodDecl>(FDecl);
786  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
787                          IsMemberOperatorCall;
788  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
789                                                  TheCall->getCallee());
790  unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
791  Expr** Args = TheCall->getArgs();
792  unsigned NumArgs = TheCall->getNumArgs();
793  if (IsMemberOperatorCall) {
794    // If this is a call to a member operator, hide the first argument
795    // from checkCall.
796    // FIXME: Our choice of AST representation here is less than ideal.
797    ++Args;
798    --NumArgs;
799  }
800  checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
801            NumProtoArgs,
802            IsMemberFunction, TheCall->getRParenLoc(),
803            TheCall->getCallee()->getSourceRange(), CallType);
804
805  IdentifierInfo *FnInfo = FDecl->getIdentifier();
806  // None of the checks below are needed for functions that don't have
807  // simple names (e.g., C++ conversion functions).
808  if (!FnInfo)
809    return false;
810
811  unsigned CMId = FDecl->getMemoryFunctionKind();
812  if (CMId == 0)
813    return false;
814
815  // Handle memory setting and copying functions.
816  if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
817    CheckStrlcpycatArguments(TheCall, FnInfo);
818  else if (CMId == Builtin::BIstrncat)
819    CheckStrncatArguments(TheCall, FnInfo);
820  else
821    CheckMemaccessArguments(TheCall, CMId, FnInfo);
822
823  return false;
824}
825
826bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
827                               ArrayRef<const Expr *> Args) {
828  VariadicCallType CallType =
829      Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
830
831  checkCall(Method, Args, Method->param_size(),
832            /*IsMemberFunction=*/false,
833            lbrac, Method->getSourceRange(), CallType);
834
835  return false;
836}
837
838bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
839                            const FunctionProtoType *Proto) {
840  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
841  if (!V)
842    return false;
843
844  QualType Ty = V->getType();
845  if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
846    return false;
847
848  VariadicCallType CallType;
849  if (!Proto || !Proto->isVariadic()) {
850    CallType = VariadicDoesNotApply;
851  } else if (Ty->isBlockPointerType()) {
852    CallType = VariadicBlock;
853  } else { // Ty->isFunctionPointerType()
854    CallType = VariadicFunction;
855  }
856  unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
857
858  checkCall(NDecl,
859            llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
860                                             TheCall->getNumArgs()),
861            NumProtoArgs, /*IsMemberFunction=*/false,
862            TheCall->getRParenLoc(),
863            TheCall->getCallee()->getSourceRange(), CallType);
864
865  return false;
866}
867
868/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
869/// such as function pointers returned from functions.
870bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
871  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
872                                                  TheCall->getCallee());
873  unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
874
875  checkCall(/*FDecl=*/0,
876            llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
877                                             TheCall->getNumArgs()),
878            NumProtoArgs, /*IsMemberFunction=*/false,
879            TheCall->getRParenLoc(),
880            TheCall->getCallee()->getSourceRange(), CallType);
881
882  return false;
883}
884
885ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
886                                         AtomicExpr::AtomicOp Op) {
887  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
888  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
889
890  // All these operations take one of the following forms:
891  enum {
892    // C    __c11_atomic_init(A *, C)
893    Init,
894    // C    __c11_atomic_load(A *, int)
895    Load,
896    // void __atomic_load(A *, CP, int)
897    Copy,
898    // C    __c11_atomic_add(A *, M, int)
899    Arithmetic,
900    // C    __atomic_exchange_n(A *, CP, int)
901    Xchg,
902    // void __atomic_exchange(A *, C *, CP, int)
903    GNUXchg,
904    // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
905    C11CmpXchg,
906    // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
907    GNUCmpXchg
908  } Form = Init;
909  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
910  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
911  // where:
912  //   C is an appropriate type,
913  //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
914  //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
915  //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
916  //   the int parameters are for orderings.
917
918  assert(AtomicExpr::AO__c11_atomic_init == 0 &&
919         AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
920         && "need to update code for modified C11 atomics");
921  bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
922               Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
923  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
924             Op == AtomicExpr::AO__atomic_store_n ||
925             Op == AtomicExpr::AO__atomic_exchange_n ||
926             Op == AtomicExpr::AO__atomic_compare_exchange_n;
927  bool IsAddSub = false;
928
929  switch (Op) {
930  case AtomicExpr::AO__c11_atomic_init:
931    Form = Init;
932    break;
933
934  case AtomicExpr::AO__c11_atomic_load:
935  case AtomicExpr::AO__atomic_load_n:
936    Form = Load;
937    break;
938
939  case AtomicExpr::AO__c11_atomic_store:
940  case AtomicExpr::AO__atomic_load:
941  case AtomicExpr::AO__atomic_store:
942  case AtomicExpr::AO__atomic_store_n:
943    Form = Copy;
944    break;
945
946  case AtomicExpr::AO__c11_atomic_fetch_add:
947  case AtomicExpr::AO__c11_atomic_fetch_sub:
948  case AtomicExpr::AO__atomic_fetch_add:
949  case AtomicExpr::AO__atomic_fetch_sub:
950  case AtomicExpr::AO__atomic_add_fetch:
951  case AtomicExpr::AO__atomic_sub_fetch:
952    IsAddSub = true;
953    // Fall through.
954  case AtomicExpr::AO__c11_atomic_fetch_and:
955  case AtomicExpr::AO__c11_atomic_fetch_or:
956  case AtomicExpr::AO__c11_atomic_fetch_xor:
957  case AtomicExpr::AO__atomic_fetch_and:
958  case AtomicExpr::AO__atomic_fetch_or:
959  case AtomicExpr::AO__atomic_fetch_xor:
960  case AtomicExpr::AO__atomic_fetch_nand:
961  case AtomicExpr::AO__atomic_and_fetch:
962  case AtomicExpr::AO__atomic_or_fetch:
963  case AtomicExpr::AO__atomic_xor_fetch:
964  case AtomicExpr::AO__atomic_nand_fetch:
965    Form = Arithmetic;
966    break;
967
968  case AtomicExpr::AO__c11_atomic_exchange:
969  case AtomicExpr::AO__atomic_exchange_n:
970    Form = Xchg;
971    break;
972
973  case AtomicExpr::AO__atomic_exchange:
974    Form = GNUXchg;
975    break;
976
977  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
978  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
979    Form = C11CmpXchg;
980    break;
981
982  case AtomicExpr::AO__atomic_compare_exchange:
983  case AtomicExpr::AO__atomic_compare_exchange_n:
984    Form = GNUCmpXchg;
985    break;
986  }
987
988  // Check we have the right number of arguments.
989  if (TheCall->getNumArgs() < NumArgs[Form]) {
990    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
991      << 0 << NumArgs[Form] << TheCall->getNumArgs()
992      << TheCall->getCallee()->getSourceRange();
993    return ExprError();
994  } else if (TheCall->getNumArgs() > NumArgs[Form]) {
995    Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
996         diag::err_typecheck_call_too_many_args)
997      << 0 << NumArgs[Form] << TheCall->getNumArgs()
998      << TheCall->getCallee()->getSourceRange();
999    return ExprError();
1000  }
1001
1002  // Inspect the first argument of the atomic operation.
1003  Expr *Ptr = TheCall->getArg(0);
1004  Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1005  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1006  if (!pointerType) {
1007    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1008      << Ptr->getType() << Ptr->getSourceRange();
1009    return ExprError();
1010  }
1011
1012  // For a __c11 builtin, this should be a pointer to an _Atomic type.
1013  QualType AtomTy = pointerType->getPointeeType(); // 'A'
1014  QualType ValType = AtomTy; // 'C'
1015  if (IsC11) {
1016    if (!AtomTy->isAtomicType()) {
1017      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1018        << Ptr->getType() << Ptr->getSourceRange();
1019      return ExprError();
1020    }
1021    if (AtomTy.isConstQualified()) {
1022      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1023        << Ptr->getType() << Ptr->getSourceRange();
1024      return ExprError();
1025    }
1026    ValType = AtomTy->getAs<AtomicType>()->getValueType();
1027  }
1028
1029  // For an arithmetic operation, the implied arithmetic must be well-formed.
1030  if (Form == Arithmetic) {
1031    // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1032    if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1033      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1034        << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1035      return ExprError();
1036    }
1037    if (!IsAddSub && !ValType->isIntegerType()) {
1038      Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1039        << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1040      return ExprError();
1041    }
1042  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1043    // For __atomic_*_n operations, the value type must be a scalar integral or
1044    // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1045    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1046      << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1047    return ExprError();
1048  }
1049
1050  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1051      !AtomTy->isScalarType()) {
1052    // For GNU atomics, require a trivially-copyable type. This is not part of
1053    // the GNU atomics specification, but we enforce it for sanity.
1054    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1055      << Ptr->getType() << Ptr->getSourceRange();
1056    return ExprError();
1057  }
1058
1059  // FIXME: For any builtin other than a load, the ValType must not be
1060  // const-qualified.
1061
1062  switch (ValType.getObjCLifetime()) {
1063  case Qualifiers::OCL_None:
1064  case Qualifiers::OCL_ExplicitNone:
1065    // okay
1066    break;
1067
1068  case Qualifiers::OCL_Weak:
1069  case Qualifiers::OCL_Strong:
1070  case Qualifiers::OCL_Autoreleasing:
1071    // FIXME: Can this happen? By this point, ValType should be known
1072    // to be trivially copyable.
1073    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1074      << ValType << Ptr->getSourceRange();
1075    return ExprError();
1076  }
1077
1078  QualType ResultType = ValType;
1079  if (Form == Copy || Form == GNUXchg || Form == Init)
1080    ResultType = Context.VoidTy;
1081  else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1082    ResultType = Context.BoolTy;
1083
1084  // The type of a parameter passed 'by value'. In the GNU atomics, such
1085  // arguments are actually passed as pointers.
1086  QualType ByValType = ValType; // 'CP'
1087  if (!IsC11 && !IsN)
1088    ByValType = Ptr->getType();
1089
1090  // The first argument --- the pointer --- has a fixed type; we
1091  // deduce the types of the rest of the arguments accordingly.  Walk
1092  // the remaining arguments, converting them to the deduced value type.
1093  for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1094    QualType Ty;
1095    if (i < NumVals[Form] + 1) {
1096      switch (i) {
1097      case 1:
1098        // The second argument is the non-atomic operand. For arithmetic, this
1099        // is always passed by value, and for a compare_exchange it is always
1100        // passed by address. For the rest, GNU uses by-address and C11 uses
1101        // by-value.
1102        assert(Form != Load);
1103        if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1104          Ty = ValType;
1105        else if (Form == Copy || Form == Xchg)
1106          Ty = ByValType;
1107        else if (Form == Arithmetic)
1108          Ty = Context.getPointerDiffType();
1109        else
1110          Ty = Context.getPointerType(ValType.getUnqualifiedType());
1111        break;
1112      case 2:
1113        // The third argument to compare_exchange / GNU exchange is a
1114        // (pointer to a) desired value.
1115        Ty = ByValType;
1116        break;
1117      case 3:
1118        // The fourth argument to GNU compare_exchange is a 'weak' flag.
1119        Ty = Context.BoolTy;
1120        break;
1121      }
1122    } else {
1123      // The order(s) are always converted to int.
1124      Ty = Context.IntTy;
1125    }
1126
1127    InitializedEntity Entity =
1128        InitializedEntity::InitializeParameter(Context, Ty, false);
1129    ExprResult Arg = TheCall->getArg(i);
1130    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1131    if (Arg.isInvalid())
1132      return true;
1133    TheCall->setArg(i, Arg.get());
1134  }
1135
1136  // Permute the arguments into a 'consistent' order.
1137  SmallVector<Expr*, 5> SubExprs;
1138  SubExprs.push_back(Ptr);
1139  switch (Form) {
1140  case Init:
1141    // Note, AtomicExpr::getVal1() has a special case for this atomic.
1142    SubExprs.push_back(TheCall->getArg(1)); // Val1
1143    break;
1144  case Load:
1145    SubExprs.push_back(TheCall->getArg(1)); // Order
1146    break;
1147  case Copy:
1148  case Arithmetic:
1149  case Xchg:
1150    SubExprs.push_back(TheCall->getArg(2)); // Order
1151    SubExprs.push_back(TheCall->getArg(1)); // Val1
1152    break;
1153  case GNUXchg:
1154    // Note, AtomicExpr::getVal2() has a special case for this atomic.
1155    SubExprs.push_back(TheCall->getArg(3)); // Order
1156    SubExprs.push_back(TheCall->getArg(1)); // Val1
1157    SubExprs.push_back(TheCall->getArg(2)); // Val2
1158    break;
1159  case C11CmpXchg:
1160    SubExprs.push_back(TheCall->getArg(3)); // Order
1161    SubExprs.push_back(TheCall->getArg(1)); // Val1
1162    SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1163    SubExprs.push_back(TheCall->getArg(2)); // Val2
1164    break;
1165  case GNUCmpXchg:
1166    SubExprs.push_back(TheCall->getArg(4)); // Order
1167    SubExprs.push_back(TheCall->getArg(1)); // Val1
1168    SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1169    SubExprs.push_back(TheCall->getArg(2)); // Val2
1170    SubExprs.push_back(TheCall->getArg(3)); // Weak
1171    break;
1172  }
1173
1174  AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1175                                            SubExprs, ResultType, Op,
1176                                            TheCall->getRParenLoc());
1177
1178  if ((Op == AtomicExpr::AO__c11_atomic_load ||
1179       (Op == AtomicExpr::AO__c11_atomic_store)) &&
1180      Context.AtomicUsesUnsupportedLibcall(AE))
1181    Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1182    ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1183
1184  return Owned(AE);
1185}
1186
1187
1188/// checkBuiltinArgument - Given a call to a builtin function, perform
1189/// normal type-checking on the given argument, updating the call in
1190/// place.  This is useful when a builtin function requires custom
1191/// type-checking for some of its arguments but not necessarily all of
1192/// them.
1193///
1194/// Returns true on error.
1195static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1196  FunctionDecl *Fn = E->getDirectCallee();
1197  assert(Fn && "builtin call without direct callee!");
1198
1199  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1200  InitializedEntity Entity =
1201    InitializedEntity::InitializeParameter(S.Context, Param);
1202
1203  ExprResult Arg = E->getArg(0);
1204  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1205  if (Arg.isInvalid())
1206    return true;
1207
1208  E->setArg(ArgIndex, Arg.take());
1209  return false;
1210}
1211
1212/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1213/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1214/// type of its first argument.  The main ActOnCallExpr routines have already
1215/// promoted the types of arguments because all of these calls are prototyped as
1216/// void(...).
1217///
1218/// This function goes through and does final semantic checking for these
1219/// builtins,
1220ExprResult
1221Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1222  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1223  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1224  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1225
1226  // Ensure that we have at least one argument to do type inference from.
1227  if (TheCall->getNumArgs() < 1) {
1228    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1229      << 0 << 1 << TheCall->getNumArgs()
1230      << TheCall->getCallee()->getSourceRange();
1231    return ExprError();
1232  }
1233
1234  // Inspect the first argument of the atomic builtin.  This should always be
1235  // a pointer type, whose element is an integral scalar or pointer type.
1236  // Because it is a pointer type, we don't have to worry about any implicit
1237  // casts here.
1238  // FIXME: We don't allow floating point scalars as input.
1239  Expr *FirstArg = TheCall->getArg(0);
1240  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1241  if (FirstArgResult.isInvalid())
1242    return ExprError();
1243  FirstArg = FirstArgResult.take();
1244  TheCall->setArg(0, FirstArg);
1245
1246  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1247  if (!pointerType) {
1248    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1249      << FirstArg->getType() << FirstArg->getSourceRange();
1250    return ExprError();
1251  }
1252
1253  QualType ValType = pointerType->getPointeeType();
1254  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1255      !ValType->isBlockPointerType()) {
1256    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1257      << FirstArg->getType() << FirstArg->getSourceRange();
1258    return ExprError();
1259  }
1260
1261  switch (ValType.getObjCLifetime()) {
1262  case Qualifiers::OCL_None:
1263  case Qualifiers::OCL_ExplicitNone:
1264    // okay
1265    break;
1266
1267  case Qualifiers::OCL_Weak:
1268  case Qualifiers::OCL_Strong:
1269  case Qualifiers::OCL_Autoreleasing:
1270    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1271      << ValType << FirstArg->getSourceRange();
1272    return ExprError();
1273  }
1274
1275  // Strip any qualifiers off ValType.
1276  ValType = ValType.getUnqualifiedType();
1277
1278  // The majority of builtins return a value, but a few have special return
1279  // types, so allow them to override appropriately below.
1280  QualType ResultType = ValType;
1281
1282  // We need to figure out which concrete builtin this maps onto.  For example,
1283  // __sync_fetch_and_add with a 2 byte object turns into
1284  // __sync_fetch_and_add_2.
1285#define BUILTIN_ROW(x) \
1286  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1287    Builtin::BI##x##_8, Builtin::BI##x##_16 }
1288
1289  static const unsigned BuiltinIndices[][5] = {
1290    BUILTIN_ROW(__sync_fetch_and_add),
1291    BUILTIN_ROW(__sync_fetch_and_sub),
1292    BUILTIN_ROW(__sync_fetch_and_or),
1293    BUILTIN_ROW(__sync_fetch_and_and),
1294    BUILTIN_ROW(__sync_fetch_and_xor),
1295
1296    BUILTIN_ROW(__sync_add_and_fetch),
1297    BUILTIN_ROW(__sync_sub_and_fetch),
1298    BUILTIN_ROW(__sync_and_and_fetch),
1299    BUILTIN_ROW(__sync_or_and_fetch),
1300    BUILTIN_ROW(__sync_xor_and_fetch),
1301
1302    BUILTIN_ROW(__sync_val_compare_and_swap),
1303    BUILTIN_ROW(__sync_bool_compare_and_swap),
1304    BUILTIN_ROW(__sync_lock_test_and_set),
1305    BUILTIN_ROW(__sync_lock_release),
1306    BUILTIN_ROW(__sync_swap)
1307  };
1308#undef BUILTIN_ROW
1309
1310  // Determine the index of the size.
1311  unsigned SizeIndex;
1312  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1313  case 1: SizeIndex = 0; break;
1314  case 2: SizeIndex = 1; break;
1315  case 4: SizeIndex = 2; break;
1316  case 8: SizeIndex = 3; break;
1317  case 16: SizeIndex = 4; break;
1318  default:
1319    Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1320      << FirstArg->getType() << FirstArg->getSourceRange();
1321    return ExprError();
1322  }
1323
1324  // Each of these builtins has one pointer argument, followed by some number of
1325  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1326  // that we ignore.  Find out which row of BuiltinIndices to read from as well
1327  // as the number of fixed args.
1328  unsigned BuiltinID = FDecl->getBuiltinID();
1329  unsigned BuiltinIndex, NumFixed = 1;
1330  switch (BuiltinID) {
1331  default: llvm_unreachable("Unknown overloaded atomic builtin!");
1332  case Builtin::BI__sync_fetch_and_add:
1333  case Builtin::BI__sync_fetch_and_add_1:
1334  case Builtin::BI__sync_fetch_and_add_2:
1335  case Builtin::BI__sync_fetch_and_add_4:
1336  case Builtin::BI__sync_fetch_and_add_8:
1337  case Builtin::BI__sync_fetch_and_add_16:
1338    BuiltinIndex = 0;
1339    break;
1340
1341  case Builtin::BI__sync_fetch_and_sub:
1342  case Builtin::BI__sync_fetch_and_sub_1:
1343  case Builtin::BI__sync_fetch_and_sub_2:
1344  case Builtin::BI__sync_fetch_and_sub_4:
1345  case Builtin::BI__sync_fetch_and_sub_8:
1346  case Builtin::BI__sync_fetch_and_sub_16:
1347    BuiltinIndex = 1;
1348    break;
1349
1350  case Builtin::BI__sync_fetch_and_or:
1351  case Builtin::BI__sync_fetch_and_or_1:
1352  case Builtin::BI__sync_fetch_and_or_2:
1353  case Builtin::BI__sync_fetch_and_or_4:
1354  case Builtin::BI__sync_fetch_and_or_8:
1355  case Builtin::BI__sync_fetch_and_or_16:
1356    BuiltinIndex = 2;
1357    break;
1358
1359  case Builtin::BI__sync_fetch_and_and:
1360  case Builtin::BI__sync_fetch_and_and_1:
1361  case Builtin::BI__sync_fetch_and_and_2:
1362  case Builtin::BI__sync_fetch_and_and_4:
1363  case Builtin::BI__sync_fetch_and_and_8:
1364  case Builtin::BI__sync_fetch_and_and_16:
1365    BuiltinIndex = 3;
1366    break;
1367
1368  case Builtin::BI__sync_fetch_and_xor:
1369  case Builtin::BI__sync_fetch_and_xor_1:
1370  case Builtin::BI__sync_fetch_and_xor_2:
1371  case Builtin::BI__sync_fetch_and_xor_4:
1372  case Builtin::BI__sync_fetch_and_xor_8:
1373  case Builtin::BI__sync_fetch_and_xor_16:
1374    BuiltinIndex = 4;
1375    break;
1376
1377  case Builtin::BI__sync_add_and_fetch:
1378  case Builtin::BI__sync_add_and_fetch_1:
1379  case Builtin::BI__sync_add_and_fetch_2:
1380  case Builtin::BI__sync_add_and_fetch_4:
1381  case Builtin::BI__sync_add_and_fetch_8:
1382  case Builtin::BI__sync_add_and_fetch_16:
1383    BuiltinIndex = 5;
1384    break;
1385
1386  case Builtin::BI__sync_sub_and_fetch:
1387  case Builtin::BI__sync_sub_and_fetch_1:
1388  case Builtin::BI__sync_sub_and_fetch_2:
1389  case Builtin::BI__sync_sub_and_fetch_4:
1390  case Builtin::BI__sync_sub_and_fetch_8:
1391  case Builtin::BI__sync_sub_and_fetch_16:
1392    BuiltinIndex = 6;
1393    break;
1394
1395  case Builtin::BI__sync_and_and_fetch:
1396  case Builtin::BI__sync_and_and_fetch_1:
1397  case Builtin::BI__sync_and_and_fetch_2:
1398  case Builtin::BI__sync_and_and_fetch_4:
1399  case Builtin::BI__sync_and_and_fetch_8:
1400  case Builtin::BI__sync_and_and_fetch_16:
1401    BuiltinIndex = 7;
1402    break;
1403
1404  case Builtin::BI__sync_or_and_fetch:
1405  case Builtin::BI__sync_or_and_fetch_1:
1406  case Builtin::BI__sync_or_and_fetch_2:
1407  case Builtin::BI__sync_or_and_fetch_4:
1408  case Builtin::BI__sync_or_and_fetch_8:
1409  case Builtin::BI__sync_or_and_fetch_16:
1410    BuiltinIndex = 8;
1411    break;
1412
1413  case Builtin::BI__sync_xor_and_fetch:
1414  case Builtin::BI__sync_xor_and_fetch_1:
1415  case Builtin::BI__sync_xor_and_fetch_2:
1416  case Builtin::BI__sync_xor_and_fetch_4:
1417  case Builtin::BI__sync_xor_and_fetch_8:
1418  case Builtin::BI__sync_xor_and_fetch_16:
1419    BuiltinIndex = 9;
1420    break;
1421
1422  case Builtin::BI__sync_val_compare_and_swap:
1423  case Builtin::BI__sync_val_compare_and_swap_1:
1424  case Builtin::BI__sync_val_compare_and_swap_2:
1425  case Builtin::BI__sync_val_compare_and_swap_4:
1426  case Builtin::BI__sync_val_compare_and_swap_8:
1427  case Builtin::BI__sync_val_compare_and_swap_16:
1428    BuiltinIndex = 10;
1429    NumFixed = 2;
1430    break;
1431
1432  case Builtin::BI__sync_bool_compare_and_swap:
1433  case Builtin::BI__sync_bool_compare_and_swap_1:
1434  case Builtin::BI__sync_bool_compare_and_swap_2:
1435  case Builtin::BI__sync_bool_compare_and_swap_4:
1436  case Builtin::BI__sync_bool_compare_and_swap_8:
1437  case Builtin::BI__sync_bool_compare_and_swap_16:
1438    BuiltinIndex = 11;
1439    NumFixed = 2;
1440    ResultType = Context.BoolTy;
1441    break;
1442
1443  case Builtin::BI__sync_lock_test_and_set:
1444  case Builtin::BI__sync_lock_test_and_set_1:
1445  case Builtin::BI__sync_lock_test_and_set_2:
1446  case Builtin::BI__sync_lock_test_and_set_4:
1447  case Builtin::BI__sync_lock_test_and_set_8:
1448  case Builtin::BI__sync_lock_test_and_set_16:
1449    BuiltinIndex = 12;
1450    break;
1451
1452  case Builtin::BI__sync_lock_release:
1453  case Builtin::BI__sync_lock_release_1:
1454  case Builtin::BI__sync_lock_release_2:
1455  case Builtin::BI__sync_lock_release_4:
1456  case Builtin::BI__sync_lock_release_8:
1457  case Builtin::BI__sync_lock_release_16:
1458    BuiltinIndex = 13;
1459    NumFixed = 0;
1460    ResultType = Context.VoidTy;
1461    break;
1462
1463  case Builtin::BI__sync_swap:
1464  case Builtin::BI__sync_swap_1:
1465  case Builtin::BI__sync_swap_2:
1466  case Builtin::BI__sync_swap_4:
1467  case Builtin::BI__sync_swap_8:
1468  case Builtin::BI__sync_swap_16:
1469    BuiltinIndex = 14;
1470    break;
1471  }
1472
1473  // Now that we know how many fixed arguments we expect, first check that we
1474  // have at least that many.
1475  if (TheCall->getNumArgs() < 1+NumFixed) {
1476    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1477      << 0 << 1+NumFixed << TheCall->getNumArgs()
1478      << TheCall->getCallee()->getSourceRange();
1479    return ExprError();
1480  }
1481
1482  // Get the decl for the concrete builtin from this, we can tell what the
1483  // concrete integer type we should convert to is.
1484  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1485  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1486  FunctionDecl *NewBuiltinDecl;
1487  if (NewBuiltinID == BuiltinID)
1488    NewBuiltinDecl = FDecl;
1489  else {
1490    // Perform builtin lookup to avoid redeclaring it.
1491    DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1492    LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1493    LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1494    assert(Res.getFoundDecl());
1495    NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1496    if (NewBuiltinDecl == 0)
1497      return ExprError();
1498  }
1499
1500  // The first argument --- the pointer --- has a fixed type; we
1501  // deduce the types of the rest of the arguments accordingly.  Walk
1502  // the remaining arguments, converting them to the deduced value type.
1503  for (unsigned i = 0; i != NumFixed; ++i) {
1504    ExprResult Arg = TheCall->getArg(i+1);
1505
1506    // GCC does an implicit conversion to the pointer or integer ValType.  This
1507    // can fail in some cases (1i -> int**), check for this error case now.
1508    // Initialize the argument.
1509    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1510                                                   ValType, /*consume*/ false);
1511    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1512    if (Arg.isInvalid())
1513      return ExprError();
1514
1515    // Okay, we have something that *can* be converted to the right type.  Check
1516    // to see if there is a potentially weird extension going on here.  This can
1517    // happen when you do an atomic operation on something like an char* and
1518    // pass in 42.  The 42 gets converted to char.  This is even more strange
1519    // for things like 45.123 -> char, etc.
1520    // FIXME: Do this check.
1521    TheCall->setArg(i+1, Arg.take());
1522  }
1523
1524  ASTContext& Context = this->getASTContext();
1525
1526  // Create a new DeclRefExpr to refer to the new decl.
1527  DeclRefExpr* NewDRE = DeclRefExpr::Create(
1528      Context,
1529      DRE->getQualifierLoc(),
1530      SourceLocation(),
1531      NewBuiltinDecl,
1532      /*enclosing*/ false,
1533      DRE->getLocation(),
1534      Context.BuiltinFnTy,
1535      DRE->getValueKind());
1536
1537  // Set the callee in the CallExpr.
1538  // FIXME: This loses syntactic information.
1539  QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1540  ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1541                                              CK_BuiltinFnToFnPtr);
1542  TheCall->setCallee(PromotedCall.take());
1543
1544  // Change the result type of the call to match the original value type. This
1545  // is arbitrary, but the codegen for these builtins ins design to handle it
1546  // gracefully.
1547  TheCall->setType(ResultType);
1548
1549  return TheCallResult;
1550}
1551
1552/// CheckObjCString - Checks that the argument to the builtin
1553/// CFString constructor is correct
1554/// Note: It might also make sense to do the UTF-16 conversion here (would
1555/// simplify the backend).
1556bool Sema::CheckObjCString(Expr *Arg) {
1557  Arg = Arg->IgnoreParenCasts();
1558  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1559
1560  if (!Literal || !Literal->isAscii()) {
1561    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1562      << Arg->getSourceRange();
1563    return true;
1564  }
1565
1566  if (Literal->containsNonAsciiOrNull()) {
1567    StringRef String = Literal->getString();
1568    unsigned NumBytes = String.size();
1569    SmallVector<UTF16, 128> ToBuf(NumBytes);
1570    const UTF8 *FromPtr = (const UTF8 *)String.data();
1571    UTF16 *ToPtr = &ToBuf[0];
1572
1573    ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1574                                                 &ToPtr, ToPtr + NumBytes,
1575                                                 strictConversion);
1576    // Check for conversion failure.
1577    if (Result != conversionOK)
1578      Diag(Arg->getLocStart(),
1579           diag::warn_cfstring_truncated) << Arg->getSourceRange();
1580  }
1581  return false;
1582}
1583
1584/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1585/// Emit an error and return true on failure, return false on success.
1586bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1587  Expr *Fn = TheCall->getCallee();
1588  if (TheCall->getNumArgs() > 2) {
1589    Diag(TheCall->getArg(2)->getLocStart(),
1590         diag::err_typecheck_call_too_many_args)
1591      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1592      << Fn->getSourceRange()
1593      << SourceRange(TheCall->getArg(2)->getLocStart(),
1594                     (*(TheCall->arg_end()-1))->getLocEnd());
1595    return true;
1596  }
1597
1598  if (TheCall->getNumArgs() < 2) {
1599    return Diag(TheCall->getLocEnd(),
1600      diag::err_typecheck_call_too_few_args_at_least)
1601      << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1602  }
1603
1604  // Type-check the first argument normally.
1605  if (checkBuiltinArgument(*this, TheCall, 0))
1606    return true;
1607
1608  // Determine whether the current function is variadic or not.
1609  BlockScopeInfo *CurBlock = getCurBlock();
1610  bool isVariadic;
1611  if (CurBlock)
1612    isVariadic = CurBlock->TheDecl->isVariadic();
1613  else if (FunctionDecl *FD = getCurFunctionDecl())
1614    isVariadic = FD->isVariadic();
1615  else
1616    isVariadic = getCurMethodDecl()->isVariadic();
1617
1618  if (!isVariadic) {
1619    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1620    return true;
1621  }
1622
1623  // Verify that the second argument to the builtin is the last argument of the
1624  // current function or method.
1625  bool SecondArgIsLastNamedArgument = false;
1626  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1627
1628  // These are valid if SecondArgIsLastNamedArgument is false after the next
1629  // block.
1630  QualType Type;
1631  SourceLocation ParamLoc;
1632
1633  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1634    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1635      // FIXME: This isn't correct for methods (results in bogus warning).
1636      // Get the last formal in the current function.
1637      const ParmVarDecl *LastArg;
1638      if (CurBlock)
1639        LastArg = *(CurBlock->TheDecl->param_end()-1);
1640      else if (FunctionDecl *FD = getCurFunctionDecl())
1641        LastArg = *(FD->param_end()-1);
1642      else
1643        LastArg = *(getCurMethodDecl()->param_end()-1);
1644      SecondArgIsLastNamedArgument = PV == LastArg;
1645
1646      Type = PV->getType();
1647      ParamLoc = PV->getLocation();
1648    }
1649  }
1650
1651  if (!SecondArgIsLastNamedArgument)
1652    Diag(TheCall->getArg(1)->getLocStart(),
1653         diag::warn_second_parameter_of_va_start_not_last_named_argument);
1654  else if (Type->isReferenceType()) {
1655    Diag(Arg->getLocStart(),
1656         diag::warn_va_start_of_reference_type_is_undefined);
1657    Diag(ParamLoc, diag::note_parameter_type) << Type;
1658  }
1659
1660  TheCall->setType(Context.VoidTy);
1661  return false;
1662}
1663
1664/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1665/// friends.  This is declared to take (...), so we have to check everything.
1666bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1667  if (TheCall->getNumArgs() < 2)
1668    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1669      << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1670  if (TheCall->getNumArgs() > 2)
1671    return Diag(TheCall->getArg(2)->getLocStart(),
1672                diag::err_typecheck_call_too_many_args)
1673      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1674      << SourceRange(TheCall->getArg(2)->getLocStart(),
1675                     (*(TheCall->arg_end()-1))->getLocEnd());
1676
1677  ExprResult OrigArg0 = TheCall->getArg(0);
1678  ExprResult OrigArg1 = TheCall->getArg(1);
1679
1680  // Do standard promotions between the two arguments, returning their common
1681  // type.
1682  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1683  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1684    return true;
1685
1686  // Make sure any conversions are pushed back into the call; this is
1687  // type safe since unordered compare builtins are declared as "_Bool
1688  // foo(...)".
1689  TheCall->setArg(0, OrigArg0.get());
1690  TheCall->setArg(1, OrigArg1.get());
1691
1692  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1693    return false;
1694
1695  // If the common type isn't a real floating type, then the arguments were
1696  // invalid for this operation.
1697  if (Res.isNull() || !Res->isRealFloatingType())
1698    return Diag(OrigArg0.get()->getLocStart(),
1699                diag::err_typecheck_call_invalid_ordered_compare)
1700      << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1701      << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1702
1703  return false;
1704}
1705
1706/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1707/// __builtin_isnan and friends.  This is declared to take (...), so we have
1708/// to check everything. We expect the last argument to be a floating point
1709/// value.
1710bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1711  if (TheCall->getNumArgs() < NumArgs)
1712    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1713      << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1714  if (TheCall->getNumArgs() > NumArgs)
1715    return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1716                diag::err_typecheck_call_too_many_args)
1717      << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1718      << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1719                     (*(TheCall->arg_end()-1))->getLocEnd());
1720
1721  Expr *OrigArg = TheCall->getArg(NumArgs-1);
1722
1723  if (OrigArg->isTypeDependent())
1724    return false;
1725
1726  // This operation requires a non-_Complex floating-point number.
1727  if (!OrigArg->getType()->isRealFloatingType())
1728    return Diag(OrigArg->getLocStart(),
1729                diag::err_typecheck_call_invalid_unary_fp)
1730      << OrigArg->getType() << OrigArg->getSourceRange();
1731
1732  // If this is an implicit conversion from float -> double, remove it.
1733  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1734    Expr *CastArg = Cast->getSubExpr();
1735    if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1736      assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1737             "promotion from float to double is the only expected cast here");
1738      Cast->setSubExpr(0);
1739      TheCall->setArg(NumArgs-1, CastArg);
1740    }
1741  }
1742
1743  return false;
1744}
1745
1746/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1747// This is declared to take (...), so we have to check everything.
1748ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1749  if (TheCall->getNumArgs() < 2)
1750    return ExprError(Diag(TheCall->getLocEnd(),
1751                          diag::err_typecheck_call_too_few_args_at_least)
1752                     << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1753                     << TheCall->getSourceRange());
1754
1755  // Determine which of the following types of shufflevector we're checking:
1756  // 1) unary, vector mask: (lhs, mask)
1757  // 2) binary, vector mask: (lhs, rhs, mask)
1758  // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1759  QualType resType = TheCall->getArg(0)->getType();
1760  unsigned numElements = 0;
1761
1762  if (!TheCall->getArg(0)->isTypeDependent() &&
1763      !TheCall->getArg(1)->isTypeDependent()) {
1764    QualType LHSType = TheCall->getArg(0)->getType();
1765    QualType RHSType = TheCall->getArg(1)->getType();
1766
1767    if (!LHSType->isVectorType() || !RHSType->isVectorType())
1768      return ExprError(Diag(TheCall->getLocStart(),
1769                            diag::err_shufflevector_non_vector)
1770                       << SourceRange(TheCall->getArg(0)->getLocStart(),
1771                                      TheCall->getArg(1)->getLocEnd()));
1772
1773    numElements = LHSType->getAs<VectorType>()->getNumElements();
1774    unsigned numResElements = TheCall->getNumArgs() - 2;
1775
1776    // Check to see if we have a call with 2 vector arguments, the unary shuffle
1777    // with mask.  If so, verify that RHS is an integer vector type with the
1778    // same number of elts as lhs.
1779    if (TheCall->getNumArgs() == 2) {
1780      if (!RHSType->hasIntegerRepresentation() ||
1781          RHSType->getAs<VectorType>()->getNumElements() != numElements)
1782        return ExprError(Diag(TheCall->getLocStart(),
1783                              diag::err_shufflevector_incompatible_vector)
1784                         << SourceRange(TheCall->getArg(1)->getLocStart(),
1785                                        TheCall->getArg(1)->getLocEnd()));
1786    } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1787      return ExprError(Diag(TheCall->getLocStart(),
1788                            diag::err_shufflevector_incompatible_vector)
1789                       << SourceRange(TheCall->getArg(0)->getLocStart(),
1790                                      TheCall->getArg(1)->getLocEnd()));
1791    } else if (numElements != numResElements) {
1792      QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1793      resType = Context.getVectorType(eltType, numResElements,
1794                                      VectorType::GenericVector);
1795    }
1796  }
1797
1798  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1799    if (TheCall->getArg(i)->isTypeDependent() ||
1800        TheCall->getArg(i)->isValueDependent())
1801      continue;
1802
1803    llvm::APSInt Result(32);
1804    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1805      return ExprError(Diag(TheCall->getLocStart(),
1806                            diag::err_shufflevector_nonconstant_argument)
1807                       << TheCall->getArg(i)->getSourceRange());
1808
1809    // Allow -1 which will be translated to undef in the IR.
1810    if (Result.isSigned() && Result.isAllOnesValue())
1811      continue;
1812
1813    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1814      return ExprError(Diag(TheCall->getLocStart(),
1815                            diag::err_shufflevector_argument_too_large)
1816                       << TheCall->getArg(i)->getSourceRange());
1817  }
1818
1819  SmallVector<Expr*, 32> exprs;
1820
1821  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1822    exprs.push_back(TheCall->getArg(i));
1823    TheCall->setArg(i, 0);
1824  }
1825
1826  return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
1827                                            TheCall->getCallee()->getLocStart(),
1828                                            TheCall->getRParenLoc()));
1829}
1830
1831/// SemaConvertVectorExpr - Handle __builtin_convertvector
1832ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1833                                       SourceLocation BuiltinLoc,
1834                                       SourceLocation RParenLoc) {
1835  ExprValueKind VK = VK_RValue;
1836  ExprObjectKind OK = OK_Ordinary;
1837  QualType DstTy = TInfo->getType();
1838  QualType SrcTy = E->getType();
1839
1840  if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1841    return ExprError(Diag(BuiltinLoc,
1842                          diag::err_convertvector_non_vector)
1843                     << E->getSourceRange());
1844  if (!DstTy->isVectorType() && !DstTy->isDependentType())
1845    return ExprError(Diag(BuiltinLoc,
1846                          diag::err_convertvector_non_vector_type));
1847
1848  if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1849    unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1850    unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1851    if (SrcElts != DstElts)
1852      return ExprError(Diag(BuiltinLoc,
1853                            diag::err_convertvector_incompatible_vector)
1854                       << E->getSourceRange());
1855  }
1856
1857  return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1858               BuiltinLoc, RParenLoc));
1859
1860}
1861
1862/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1863// This is declared to take (const void*, ...) and can take two
1864// optional constant int args.
1865bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1866  unsigned NumArgs = TheCall->getNumArgs();
1867
1868  if (NumArgs > 3)
1869    return Diag(TheCall->getLocEnd(),
1870             diag::err_typecheck_call_too_many_args_at_most)
1871             << 0 /*function call*/ << 3 << NumArgs
1872             << TheCall->getSourceRange();
1873
1874  // Argument 0 is checked for us and the remaining arguments must be
1875  // constant integers.
1876  for (unsigned i = 1; i != NumArgs; ++i) {
1877    Expr *Arg = TheCall->getArg(i);
1878
1879    // We can't check the value of a dependent argument.
1880    if (Arg->isTypeDependent() || Arg->isValueDependent())
1881      continue;
1882
1883    llvm::APSInt Result;
1884    if (SemaBuiltinConstantArg(TheCall, i, Result))
1885      return true;
1886
1887    // FIXME: gcc issues a warning and rewrites these to 0. These
1888    // seems especially odd for the third argument since the default
1889    // is 3.
1890    if (i == 1) {
1891      if (Result.getLimitedValue() > 1)
1892        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1893             << "0" << "1" << Arg->getSourceRange();
1894    } else {
1895      if (Result.getLimitedValue() > 3)
1896        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1897            << "0" << "3" << Arg->getSourceRange();
1898    }
1899  }
1900
1901  return false;
1902}
1903
1904/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1905/// TheCall is a constant expression.
1906bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1907                                  llvm::APSInt &Result) {
1908  Expr *Arg = TheCall->getArg(ArgNum);
1909  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1910  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1911
1912  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1913
1914  if (!Arg->isIntegerConstantExpr(Result, Context))
1915    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1916                << FDecl->getDeclName() <<  Arg->getSourceRange();
1917
1918  return false;
1919}
1920
1921/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1922/// int type). This simply type checks that type is one of the defined
1923/// constants (0-3).
1924// For compatibility check 0-3, llvm only handles 0 and 2.
1925bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1926  llvm::APSInt Result;
1927
1928  // We can't check the value of a dependent argument.
1929  if (TheCall->getArg(1)->isTypeDependent() ||
1930      TheCall->getArg(1)->isValueDependent())
1931    return false;
1932
1933  // Check constant-ness first.
1934  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1935    return true;
1936
1937  Expr *Arg = TheCall->getArg(1);
1938  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1939    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1940             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1941  }
1942
1943  return false;
1944}
1945
1946/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1947/// This checks that val is a constant 1.
1948bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1949  Expr *Arg = TheCall->getArg(1);
1950  llvm::APSInt Result;
1951
1952  // TODO: This is less than ideal. Overload this to take a value.
1953  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1954    return true;
1955
1956  if (Result != 1)
1957    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1958             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1959
1960  return false;
1961}
1962
1963namespace {
1964enum StringLiteralCheckType {
1965  SLCT_NotALiteral,
1966  SLCT_UncheckedLiteral,
1967  SLCT_CheckedLiteral
1968};
1969}
1970
1971// Determine if an expression is a string literal or constant string.
1972// If this function returns false on the arguments to a function expecting a
1973// format string, we will usually need to emit a warning.
1974// True string literals are then checked by CheckFormatString.
1975static StringLiteralCheckType
1976checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1977                      bool HasVAListArg, unsigned format_idx,
1978                      unsigned firstDataArg, Sema::FormatStringType Type,
1979                      Sema::VariadicCallType CallType, bool InFunctionCall,
1980                      llvm::SmallBitVector &CheckedVarArgs) {
1981 tryAgain:
1982  if (E->isTypeDependent() || E->isValueDependent())
1983    return SLCT_NotALiteral;
1984
1985  E = E->IgnoreParenCasts();
1986
1987  if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
1988    // Technically -Wformat-nonliteral does not warn about this case.
1989    // The behavior of printf and friends in this case is implementation
1990    // dependent.  Ideally if the format string cannot be null then
1991    // it should have a 'nonnull' attribute in the function prototype.
1992    return SLCT_UncheckedLiteral;
1993
1994  switch (E->getStmtClass()) {
1995  case Stmt::BinaryConditionalOperatorClass:
1996  case Stmt::ConditionalOperatorClass: {
1997    // The expression is a literal if both sub-expressions were, and it was
1998    // completely checked only if both sub-expressions were checked.
1999    const AbstractConditionalOperator *C =
2000        cast<AbstractConditionalOperator>(E);
2001    StringLiteralCheckType Left =
2002        checkFormatStringExpr(S, C->getTrueExpr(), Args,
2003                              HasVAListArg, format_idx, firstDataArg,
2004                              Type, CallType, InFunctionCall, CheckedVarArgs);
2005    if (Left == SLCT_NotALiteral)
2006      return SLCT_NotALiteral;
2007    StringLiteralCheckType Right =
2008        checkFormatStringExpr(S, C->getFalseExpr(), Args,
2009                              HasVAListArg, format_idx, firstDataArg,
2010                              Type, CallType, InFunctionCall, CheckedVarArgs);
2011    return Left < Right ? Left : Right;
2012  }
2013
2014  case Stmt::ImplicitCastExprClass: {
2015    E = cast<ImplicitCastExpr>(E)->getSubExpr();
2016    goto tryAgain;
2017  }
2018
2019  case Stmt::OpaqueValueExprClass:
2020    if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2021      E = src;
2022      goto tryAgain;
2023    }
2024    return SLCT_NotALiteral;
2025
2026  case Stmt::PredefinedExprClass:
2027    // While __func__, etc., are technically not string literals, they
2028    // cannot contain format specifiers and thus are not a security
2029    // liability.
2030    return SLCT_UncheckedLiteral;
2031
2032  case Stmt::DeclRefExprClass: {
2033    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2034
2035    // As an exception, do not flag errors for variables binding to
2036    // const string literals.
2037    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2038      bool isConstant = false;
2039      QualType T = DR->getType();
2040
2041      if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2042        isConstant = AT->getElementType().isConstant(S.Context);
2043      } else if (const PointerType *PT = T->getAs<PointerType>()) {
2044        isConstant = T.isConstant(S.Context) &&
2045                     PT->getPointeeType().isConstant(S.Context);
2046      } else if (T->isObjCObjectPointerType()) {
2047        // In ObjC, there is usually no "const ObjectPointer" type,
2048        // so don't check if the pointee type is constant.
2049        isConstant = T.isConstant(S.Context);
2050      }
2051
2052      if (isConstant) {
2053        if (const Expr *Init = VD->getAnyInitializer()) {
2054          // Look through initializers like const char c[] = { "foo" }
2055          if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2056            if (InitList->isStringLiteralInit())
2057              Init = InitList->getInit(0)->IgnoreParenImpCasts();
2058          }
2059          return checkFormatStringExpr(S, Init, Args,
2060                                       HasVAListArg, format_idx,
2061                                       firstDataArg, Type, CallType,
2062                                       /*InFunctionCall*/false, CheckedVarArgs);
2063        }
2064      }
2065
2066      // For vprintf* functions (i.e., HasVAListArg==true), we add a
2067      // special check to see if the format string is a function parameter
2068      // of the function calling the printf function.  If the function
2069      // has an attribute indicating it is a printf-like function, then we
2070      // should suppress warnings concerning non-literals being used in a call
2071      // to a vprintf function.  For example:
2072      //
2073      // void
2074      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2075      //      va_list ap;
2076      //      va_start(ap, fmt);
2077      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
2078      //      ...
2079      // }
2080      if (HasVAListArg) {
2081        if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2082          if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2083            int PVIndex = PV->getFunctionScopeIndex() + 1;
2084            for (specific_attr_iterator<FormatAttr>
2085                 i = ND->specific_attr_begin<FormatAttr>(),
2086                 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2087              FormatAttr *PVFormat = *i;
2088              // adjust for implicit parameter
2089              if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2090                if (MD->isInstance())
2091                  ++PVIndex;
2092              // We also check if the formats are compatible.
2093              // We can't pass a 'scanf' string to a 'printf' function.
2094              if (PVIndex == PVFormat->getFormatIdx() &&
2095                  Type == S.GetFormatStringType(PVFormat))
2096                return SLCT_UncheckedLiteral;
2097            }
2098          }
2099        }
2100      }
2101    }
2102
2103    return SLCT_NotALiteral;
2104  }
2105
2106  case Stmt::CallExprClass:
2107  case Stmt::CXXMemberCallExprClass: {
2108    const CallExpr *CE = cast<CallExpr>(E);
2109    if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2110      if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2111        unsigned ArgIndex = FA->getFormatIdx();
2112        if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2113          if (MD->isInstance())
2114            --ArgIndex;
2115        const Expr *Arg = CE->getArg(ArgIndex - 1);
2116
2117        return checkFormatStringExpr(S, Arg, Args,
2118                                     HasVAListArg, format_idx, firstDataArg,
2119                                     Type, CallType, InFunctionCall,
2120                                     CheckedVarArgs);
2121      } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2122        unsigned BuiltinID = FD->getBuiltinID();
2123        if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2124            BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2125          const Expr *Arg = CE->getArg(0);
2126          return checkFormatStringExpr(S, Arg, Args,
2127                                       HasVAListArg, format_idx,
2128                                       firstDataArg, Type, CallType,
2129                                       InFunctionCall, CheckedVarArgs);
2130        }
2131      }
2132    }
2133
2134    return SLCT_NotALiteral;
2135  }
2136
2137  case Stmt::ObjCMessageExprClass: {
2138    const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2139    if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2140      if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2141        if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2142          unsigned ArgIndex = FA->getFormatIdx();
2143          if (ArgIndex <= ME->getNumArgs()) {
2144            const Expr *Arg = ME->getArg(ArgIndex-1);
2145            return checkFormatStringExpr(S, Arg, Args,
2146                                         HasVAListArg, format_idx,
2147                                         firstDataArg, Type, CallType,
2148                                         InFunctionCall, CheckedVarArgs);
2149          }
2150        }
2151      }
2152    }
2153
2154    return SLCT_NotALiteral;
2155  }
2156
2157  case Stmt::ObjCStringLiteralClass:
2158  case Stmt::StringLiteralClass: {
2159    const StringLiteral *StrE = NULL;
2160
2161    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2162      StrE = ObjCFExpr->getString();
2163    else
2164      StrE = cast<StringLiteral>(E);
2165
2166    if (StrE) {
2167      S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2168                          Type, InFunctionCall, CallType, CheckedVarArgs);
2169      return SLCT_CheckedLiteral;
2170    }
2171
2172    return SLCT_NotALiteral;
2173  }
2174
2175  default:
2176    return SLCT_NotALiteral;
2177  }
2178}
2179
2180void
2181Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
2182                            const Expr * const *ExprArgs,
2183                            SourceLocation CallSiteLoc) {
2184  for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2185                                  e = NonNull->args_end();
2186       i != e; ++i) {
2187    const Expr *ArgExpr = ExprArgs[*i];
2188
2189    // As a special case, transparent unions initialized with zero are
2190    // considered null for the purposes of the nonnull attribute.
2191    if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2192      if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2193        if (const CompoundLiteralExpr *CLE =
2194            dyn_cast<CompoundLiteralExpr>(ArgExpr))
2195          if (const InitListExpr *ILE =
2196              dyn_cast<InitListExpr>(CLE->getInitializer()))
2197            ArgExpr = ILE->getInit(0);
2198    }
2199
2200    bool Result;
2201    if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
2202      Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
2203  }
2204}
2205
2206Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2207  return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2208  .Case("scanf", FST_Scanf)
2209  .Cases("printf", "printf0", FST_Printf)
2210  .Cases("NSString", "CFString", FST_NSString)
2211  .Case("strftime", FST_Strftime)
2212  .Case("strfmon", FST_Strfmon)
2213  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2214  .Default(FST_Unknown);
2215}
2216
2217/// CheckFormatArguments - Check calls to printf and scanf (and similar
2218/// functions) for correct use of format strings.
2219/// Returns true if a format string has been fully checked.
2220bool Sema::CheckFormatArguments(const FormatAttr *Format,
2221                                ArrayRef<const Expr *> Args,
2222                                bool IsCXXMember,
2223                                VariadicCallType CallType,
2224                                SourceLocation Loc, SourceRange Range,
2225                                llvm::SmallBitVector &CheckedVarArgs) {
2226  FormatStringInfo FSI;
2227  if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2228    return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2229                                FSI.FirstDataArg, GetFormatStringType(Format),
2230                                CallType, Loc, Range, CheckedVarArgs);
2231  return false;
2232}
2233
2234bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2235                                bool HasVAListArg, unsigned format_idx,
2236                                unsigned firstDataArg, FormatStringType Type,
2237                                VariadicCallType CallType,
2238                                SourceLocation Loc, SourceRange Range,
2239                                llvm::SmallBitVector &CheckedVarArgs) {
2240  // CHECK: printf/scanf-like function is called with no format string.
2241  if (format_idx >= Args.size()) {
2242    Diag(Loc, diag::warn_missing_format_string) << Range;
2243    return false;
2244  }
2245
2246  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2247
2248  // CHECK: format string is not a string literal.
2249  //
2250  // Dynamically generated format strings are difficult to
2251  // automatically vet at compile time.  Requiring that format strings
2252  // are string literals: (1) permits the checking of format strings by
2253  // the compiler and thereby (2) can practically remove the source of
2254  // many format string exploits.
2255
2256  // Format string can be either ObjC string (e.g. @"%d") or
2257  // C string (e.g. "%d")
2258  // ObjC string uses the same format specifiers as C string, so we can use
2259  // the same format string checking logic for both ObjC and C strings.
2260  StringLiteralCheckType CT =
2261      checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2262                            format_idx, firstDataArg, Type, CallType,
2263                            /*IsFunctionCall*/true, CheckedVarArgs);
2264  if (CT != SLCT_NotALiteral)
2265    // Literal format string found, check done!
2266    return CT == SLCT_CheckedLiteral;
2267
2268  // Strftime is particular as it always uses a single 'time' argument,
2269  // so it is safe to pass a non-literal string.
2270  if (Type == FST_Strftime)
2271    return false;
2272
2273  // Do not emit diag when the string param is a macro expansion and the
2274  // format is either NSString or CFString. This is a hack to prevent
2275  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2276  // which are usually used in place of NS and CF string literals.
2277  if (Type == FST_NSString &&
2278      SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2279    return false;
2280
2281  // If there are no arguments specified, warn with -Wformat-security, otherwise
2282  // warn only with -Wformat-nonliteral.
2283  if (Args.size() == firstDataArg)
2284    Diag(Args[format_idx]->getLocStart(),
2285         diag::warn_format_nonliteral_noargs)
2286      << OrigFormatExpr->getSourceRange();
2287  else
2288    Diag(Args[format_idx]->getLocStart(),
2289         diag::warn_format_nonliteral)
2290           << OrigFormatExpr->getSourceRange();
2291  return false;
2292}
2293
2294namespace {
2295class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2296protected:
2297  Sema &S;
2298  const StringLiteral *FExpr;
2299  const Expr *OrigFormatExpr;
2300  const unsigned FirstDataArg;
2301  const unsigned NumDataArgs;
2302  const char *Beg; // Start of format string.
2303  const bool HasVAListArg;
2304  ArrayRef<const Expr *> Args;
2305  unsigned FormatIdx;
2306  llvm::SmallBitVector CoveredArgs;
2307  bool usesPositionalArgs;
2308  bool atFirstArg;
2309  bool inFunctionCall;
2310  Sema::VariadicCallType CallType;
2311  llvm::SmallBitVector &CheckedVarArgs;
2312public:
2313  CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2314                     const Expr *origFormatExpr, unsigned firstDataArg,
2315                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
2316                     ArrayRef<const Expr *> Args,
2317                     unsigned formatIdx, bool inFunctionCall,
2318                     Sema::VariadicCallType callType,
2319                     llvm::SmallBitVector &CheckedVarArgs)
2320    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2321      FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2322      Beg(beg), HasVAListArg(hasVAListArg),
2323      Args(Args), FormatIdx(formatIdx),
2324      usesPositionalArgs(false), atFirstArg(true),
2325      inFunctionCall(inFunctionCall), CallType(callType),
2326      CheckedVarArgs(CheckedVarArgs) {
2327    CoveredArgs.resize(numDataArgs);
2328    CoveredArgs.reset();
2329  }
2330
2331  void DoneProcessing();
2332
2333  void HandleIncompleteSpecifier(const char *startSpecifier,
2334                                 unsigned specifierLen);
2335
2336  void HandleInvalidLengthModifier(
2337      const analyze_format_string::FormatSpecifier &FS,
2338      const analyze_format_string::ConversionSpecifier &CS,
2339      const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
2340
2341  void HandleNonStandardLengthModifier(
2342      const analyze_format_string::FormatSpecifier &FS,
2343      const char *startSpecifier, unsigned specifierLen);
2344
2345  void HandleNonStandardConversionSpecifier(
2346      const analyze_format_string::ConversionSpecifier &CS,
2347      const char *startSpecifier, unsigned specifierLen);
2348
2349  virtual void HandlePosition(const char *startPos, unsigned posLen);
2350
2351  virtual void HandleInvalidPosition(const char *startSpecifier,
2352                                     unsigned specifierLen,
2353                                     analyze_format_string::PositionContext p);
2354
2355  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2356
2357  void HandleNullChar(const char *nullCharacter);
2358
2359  template <typename Range>
2360  static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2361                                   const Expr *ArgumentExpr,
2362                                   PartialDiagnostic PDiag,
2363                                   SourceLocation StringLoc,
2364                                   bool IsStringLocation, Range StringRange,
2365                                   ArrayRef<FixItHint> Fixit = None);
2366
2367protected:
2368  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2369                                        const char *startSpec,
2370                                        unsigned specifierLen,
2371                                        const char *csStart, unsigned csLen);
2372
2373  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2374                                         const char *startSpec,
2375                                         unsigned specifierLen);
2376
2377  SourceRange getFormatStringRange();
2378  CharSourceRange getSpecifierRange(const char *startSpecifier,
2379                                    unsigned specifierLen);
2380  SourceLocation getLocationOfByte(const char *x);
2381
2382  const Expr *getDataArg(unsigned i) const;
2383
2384  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2385                    const analyze_format_string::ConversionSpecifier &CS,
2386                    const char *startSpecifier, unsigned specifierLen,
2387                    unsigned argIndex);
2388
2389  template <typename Range>
2390  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2391                            bool IsStringLocation, Range StringRange,
2392                            ArrayRef<FixItHint> Fixit = None);
2393
2394  void CheckPositionalAndNonpositionalArgs(
2395      const analyze_format_string::FormatSpecifier *FS);
2396};
2397}
2398
2399SourceRange CheckFormatHandler::getFormatStringRange() {
2400  return OrigFormatExpr->getSourceRange();
2401}
2402
2403CharSourceRange CheckFormatHandler::
2404getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2405  SourceLocation Start = getLocationOfByte(startSpecifier);
2406  SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
2407
2408  // Advance the end SourceLocation by one due to half-open ranges.
2409  End = End.getLocWithOffset(1);
2410
2411  return CharSourceRange::getCharRange(Start, End);
2412}
2413
2414SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2415  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2416}
2417
2418void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2419                                                   unsigned specifierLen){
2420  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2421                       getLocationOfByte(startSpecifier),
2422                       /*IsStringLocation*/true,
2423                       getSpecifierRange(startSpecifier, specifierLen));
2424}
2425
2426void CheckFormatHandler::HandleInvalidLengthModifier(
2427    const analyze_format_string::FormatSpecifier &FS,
2428    const analyze_format_string::ConversionSpecifier &CS,
2429    const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2430  using namespace analyze_format_string;
2431
2432  const LengthModifier &LM = FS.getLengthModifier();
2433  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2434
2435  // See if we know how to fix this length modifier.
2436  Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2437  if (FixedLM) {
2438    EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2439                         getLocationOfByte(LM.getStart()),
2440                         /*IsStringLocation*/true,
2441                         getSpecifierRange(startSpecifier, specifierLen));
2442
2443    S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2444      << FixedLM->toString()
2445      << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2446
2447  } else {
2448    FixItHint Hint;
2449    if (DiagID == diag::warn_format_nonsensical_length)
2450      Hint = FixItHint::CreateRemoval(LMRange);
2451
2452    EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2453                         getLocationOfByte(LM.getStart()),
2454                         /*IsStringLocation*/true,
2455                         getSpecifierRange(startSpecifier, specifierLen),
2456                         Hint);
2457  }
2458}
2459
2460void CheckFormatHandler::HandleNonStandardLengthModifier(
2461    const analyze_format_string::FormatSpecifier &FS,
2462    const char *startSpecifier, unsigned specifierLen) {
2463  using namespace analyze_format_string;
2464
2465  const LengthModifier &LM = FS.getLengthModifier();
2466  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2467
2468  // See if we know how to fix this length modifier.
2469  Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2470  if (FixedLM) {
2471    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2472                           << LM.toString() << 0,
2473                         getLocationOfByte(LM.getStart()),
2474                         /*IsStringLocation*/true,
2475                         getSpecifierRange(startSpecifier, specifierLen));
2476
2477    S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2478      << FixedLM->toString()
2479      << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2480
2481  } else {
2482    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2483                           << LM.toString() << 0,
2484                         getLocationOfByte(LM.getStart()),
2485                         /*IsStringLocation*/true,
2486                         getSpecifierRange(startSpecifier, specifierLen));
2487  }
2488}
2489
2490void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2491    const analyze_format_string::ConversionSpecifier &CS,
2492    const char *startSpecifier, unsigned specifierLen) {
2493  using namespace analyze_format_string;
2494
2495  // See if we know how to fix this conversion specifier.
2496  Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2497  if (FixedCS) {
2498    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2499                          << CS.toString() << /*conversion specifier*/1,
2500                         getLocationOfByte(CS.getStart()),
2501                         /*IsStringLocation*/true,
2502                         getSpecifierRange(startSpecifier, specifierLen));
2503
2504    CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2505    S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2506      << FixedCS->toString()
2507      << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2508  } else {
2509    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2510                          << CS.toString() << /*conversion specifier*/1,
2511                         getLocationOfByte(CS.getStart()),
2512                         /*IsStringLocation*/true,
2513                         getSpecifierRange(startSpecifier, specifierLen));
2514  }
2515}
2516
2517void CheckFormatHandler::HandlePosition(const char *startPos,
2518                                        unsigned posLen) {
2519  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2520                               getLocationOfByte(startPos),
2521                               /*IsStringLocation*/true,
2522                               getSpecifierRange(startPos, posLen));
2523}
2524
2525void
2526CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2527                                     analyze_format_string::PositionContext p) {
2528  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2529                         << (unsigned) p,
2530                       getLocationOfByte(startPos), /*IsStringLocation*/true,
2531                       getSpecifierRange(startPos, posLen));
2532}
2533
2534void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2535                                            unsigned posLen) {
2536  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2537                               getLocationOfByte(startPos),
2538                               /*IsStringLocation*/true,
2539                               getSpecifierRange(startPos, posLen));
2540}
2541
2542void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2543  if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2544    // The presence of a null character is likely an error.
2545    EmitFormatDiagnostic(
2546      S.PDiag(diag::warn_printf_format_string_contains_null_char),
2547      getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2548      getFormatStringRange());
2549  }
2550}
2551
2552// Note that this may return NULL if there was an error parsing or building
2553// one of the argument expressions.
2554const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2555  return Args[FirstDataArg + i];
2556}
2557
2558void CheckFormatHandler::DoneProcessing() {
2559    // Does the number of data arguments exceed the number of
2560    // format conversions in the format string?
2561  if (!HasVAListArg) {
2562      // Find any arguments that weren't covered.
2563    CoveredArgs.flip();
2564    signed notCoveredArg = CoveredArgs.find_first();
2565    if (notCoveredArg >= 0) {
2566      assert((unsigned)notCoveredArg < NumDataArgs);
2567      if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2568        SourceLocation Loc = E->getLocStart();
2569        if (!S.getSourceManager().isInSystemMacro(Loc)) {
2570          EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2571                               Loc, /*IsStringLocation*/false,
2572                               getFormatStringRange());
2573        }
2574      }
2575    }
2576  }
2577}
2578
2579bool
2580CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2581                                                     SourceLocation Loc,
2582                                                     const char *startSpec,
2583                                                     unsigned specifierLen,
2584                                                     const char *csStart,
2585                                                     unsigned csLen) {
2586
2587  bool keepGoing = true;
2588  if (argIndex < NumDataArgs) {
2589    // Consider the argument coverered, even though the specifier doesn't
2590    // make sense.
2591    CoveredArgs.set(argIndex);
2592  }
2593  else {
2594    // If argIndex exceeds the number of data arguments we
2595    // don't issue a warning because that is just a cascade of warnings (and
2596    // they may have intended '%%' anyway). We don't want to continue processing
2597    // the format string after this point, however, as we will like just get
2598    // gibberish when trying to match arguments.
2599    keepGoing = false;
2600  }
2601
2602  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2603                         << StringRef(csStart, csLen),
2604                       Loc, /*IsStringLocation*/true,
2605                       getSpecifierRange(startSpec, specifierLen));
2606
2607  return keepGoing;
2608}
2609
2610void
2611CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2612                                                      const char *startSpec,
2613                                                      unsigned specifierLen) {
2614  EmitFormatDiagnostic(
2615    S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2616    Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2617}
2618
2619bool
2620CheckFormatHandler::CheckNumArgs(
2621  const analyze_format_string::FormatSpecifier &FS,
2622  const analyze_format_string::ConversionSpecifier &CS,
2623  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2624
2625  if (argIndex >= NumDataArgs) {
2626    PartialDiagnostic PDiag = FS.usesPositionalArg()
2627      ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2628           << (argIndex+1) << NumDataArgs)
2629      : S.PDiag(diag::warn_printf_insufficient_data_args);
2630    EmitFormatDiagnostic(
2631      PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2632      getSpecifierRange(startSpecifier, specifierLen));
2633    return false;
2634  }
2635  return true;
2636}
2637
2638template<typename Range>
2639void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2640                                              SourceLocation Loc,
2641                                              bool IsStringLocation,
2642                                              Range StringRange,
2643                                              ArrayRef<FixItHint> FixIt) {
2644  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2645                       Loc, IsStringLocation, StringRange, FixIt);
2646}
2647
2648/// \brief If the format string is not within the funcion call, emit a note
2649/// so that the function call and string are in diagnostic messages.
2650///
2651/// \param InFunctionCall if true, the format string is within the function
2652/// call and only one diagnostic message will be produced.  Otherwise, an
2653/// extra note will be emitted pointing to location of the format string.
2654///
2655/// \param ArgumentExpr the expression that is passed as the format string
2656/// argument in the function call.  Used for getting locations when two
2657/// diagnostics are emitted.
2658///
2659/// \param PDiag the callee should already have provided any strings for the
2660/// diagnostic message.  This function only adds locations and fixits
2661/// to diagnostics.
2662///
2663/// \param Loc primary location for diagnostic.  If two diagnostics are
2664/// required, one will be at Loc and a new SourceLocation will be created for
2665/// the other one.
2666///
2667/// \param IsStringLocation if true, Loc points to the format string should be
2668/// used for the note.  Otherwise, Loc points to the argument list and will
2669/// be used with PDiag.
2670///
2671/// \param StringRange some or all of the string to highlight.  This is
2672/// templated so it can accept either a CharSourceRange or a SourceRange.
2673///
2674/// \param FixIt optional fix it hint for the format string.
2675template<typename Range>
2676void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2677                                              const Expr *ArgumentExpr,
2678                                              PartialDiagnostic PDiag,
2679                                              SourceLocation Loc,
2680                                              bool IsStringLocation,
2681                                              Range StringRange,
2682                                              ArrayRef<FixItHint> FixIt) {
2683  if (InFunctionCall) {
2684    const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2685    D << StringRange;
2686    for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2687         I != E; ++I) {
2688      D << *I;
2689    }
2690  } else {
2691    S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2692      << ArgumentExpr->getSourceRange();
2693
2694    const Sema::SemaDiagnosticBuilder &Note =
2695      S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2696             diag::note_format_string_defined);
2697
2698    Note << StringRange;
2699    for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2700         I != E; ++I) {
2701      Note << *I;
2702    }
2703  }
2704}
2705
2706//===--- CHECK: Printf format string checking ------------------------------===//
2707
2708namespace {
2709class CheckPrintfHandler : public CheckFormatHandler {
2710  bool ObjCContext;
2711public:
2712  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2713                     const Expr *origFormatExpr, unsigned firstDataArg,
2714                     unsigned numDataArgs, bool isObjC,
2715                     const char *beg, bool hasVAListArg,
2716                     ArrayRef<const Expr *> Args,
2717                     unsigned formatIdx, bool inFunctionCall,
2718                     Sema::VariadicCallType CallType,
2719                     llvm::SmallBitVector &CheckedVarArgs)
2720    : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2721                         numDataArgs, beg, hasVAListArg, Args,
2722                         formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2723      ObjCContext(isObjC)
2724  {}
2725
2726
2727  bool HandleInvalidPrintfConversionSpecifier(
2728                                      const analyze_printf::PrintfSpecifier &FS,
2729                                      const char *startSpecifier,
2730                                      unsigned specifierLen);
2731
2732  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2733                             const char *startSpecifier,
2734                             unsigned specifierLen);
2735  bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2736                       const char *StartSpecifier,
2737                       unsigned SpecifierLen,
2738                       const Expr *E);
2739
2740  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2741                    const char *startSpecifier, unsigned specifierLen);
2742  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2743                           const analyze_printf::OptionalAmount &Amt,
2744                           unsigned type,
2745                           const char *startSpecifier, unsigned specifierLen);
2746  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2747                  const analyze_printf::OptionalFlag &flag,
2748                  const char *startSpecifier, unsigned specifierLen);
2749  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2750                         const analyze_printf::OptionalFlag &ignoredFlag,
2751                         const analyze_printf::OptionalFlag &flag,
2752                         const char *startSpecifier, unsigned specifierLen);
2753  bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2754                           const Expr *E, const CharSourceRange &CSR);
2755
2756};
2757}
2758
2759bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2760                                      const analyze_printf::PrintfSpecifier &FS,
2761                                      const char *startSpecifier,
2762                                      unsigned specifierLen) {
2763  const analyze_printf::PrintfConversionSpecifier &CS =
2764    FS.getConversionSpecifier();
2765
2766  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2767                                          getLocationOfByte(CS.getStart()),
2768                                          startSpecifier, specifierLen,
2769                                          CS.getStart(), CS.getLength());
2770}
2771
2772bool CheckPrintfHandler::HandleAmount(
2773                               const analyze_format_string::OptionalAmount &Amt,
2774                               unsigned k, const char *startSpecifier,
2775                               unsigned specifierLen) {
2776
2777  if (Amt.hasDataArgument()) {
2778    if (!HasVAListArg) {
2779      unsigned argIndex = Amt.getArgIndex();
2780      if (argIndex >= NumDataArgs) {
2781        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2782                               << k,
2783                             getLocationOfByte(Amt.getStart()),
2784                             /*IsStringLocation*/true,
2785                             getSpecifierRange(startSpecifier, specifierLen));
2786        // Don't do any more checking.  We will just emit
2787        // spurious errors.
2788        return false;
2789      }
2790
2791      // Type check the data argument.  It should be an 'int'.
2792      // Although not in conformance with C99, we also allow the argument to be
2793      // an 'unsigned int' as that is a reasonably safe case.  GCC also
2794      // doesn't emit a warning for that case.
2795      CoveredArgs.set(argIndex);
2796      const Expr *Arg = getDataArg(argIndex);
2797      if (!Arg)
2798        return false;
2799
2800      QualType T = Arg->getType();
2801
2802      const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2803      assert(AT.isValid());
2804
2805      if (!AT.matchesType(S.Context, T)) {
2806        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2807                               << k << AT.getRepresentativeTypeName(S.Context)
2808                               << T << Arg->getSourceRange(),
2809                             getLocationOfByte(Amt.getStart()),
2810                             /*IsStringLocation*/true,
2811                             getSpecifierRange(startSpecifier, specifierLen));
2812        // Don't do any more checking.  We will just emit
2813        // spurious errors.
2814        return false;
2815      }
2816    }
2817  }
2818  return true;
2819}
2820
2821void CheckPrintfHandler::HandleInvalidAmount(
2822                                      const analyze_printf::PrintfSpecifier &FS,
2823                                      const analyze_printf::OptionalAmount &Amt,
2824                                      unsigned type,
2825                                      const char *startSpecifier,
2826                                      unsigned specifierLen) {
2827  const analyze_printf::PrintfConversionSpecifier &CS =
2828    FS.getConversionSpecifier();
2829
2830  FixItHint fixit =
2831    Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2832      ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2833                                 Amt.getConstantLength()))
2834      : FixItHint();
2835
2836  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2837                         << type << CS.toString(),
2838                       getLocationOfByte(Amt.getStart()),
2839                       /*IsStringLocation*/true,
2840                       getSpecifierRange(startSpecifier, specifierLen),
2841                       fixit);
2842}
2843
2844void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2845                                    const analyze_printf::OptionalFlag &flag,
2846                                    const char *startSpecifier,
2847                                    unsigned specifierLen) {
2848  // Warn about pointless flag with a fixit removal.
2849  const analyze_printf::PrintfConversionSpecifier &CS =
2850    FS.getConversionSpecifier();
2851  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2852                         << flag.toString() << CS.toString(),
2853                       getLocationOfByte(flag.getPosition()),
2854                       /*IsStringLocation*/true,
2855                       getSpecifierRange(startSpecifier, specifierLen),
2856                       FixItHint::CreateRemoval(
2857                         getSpecifierRange(flag.getPosition(), 1)));
2858}
2859
2860void CheckPrintfHandler::HandleIgnoredFlag(
2861                                const analyze_printf::PrintfSpecifier &FS,
2862                                const analyze_printf::OptionalFlag &ignoredFlag,
2863                                const analyze_printf::OptionalFlag &flag,
2864                                const char *startSpecifier,
2865                                unsigned specifierLen) {
2866  // Warn about ignored flag with a fixit removal.
2867  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2868                         << ignoredFlag.toString() << flag.toString(),
2869                       getLocationOfByte(ignoredFlag.getPosition()),
2870                       /*IsStringLocation*/true,
2871                       getSpecifierRange(startSpecifier, specifierLen),
2872                       FixItHint::CreateRemoval(
2873                         getSpecifierRange(ignoredFlag.getPosition(), 1)));
2874}
2875
2876// Determines if the specified is a C++ class or struct containing
2877// a member with the specified name and kind (e.g. a CXXMethodDecl named
2878// "c_str()").
2879template<typename MemberKind>
2880static llvm::SmallPtrSet<MemberKind*, 1>
2881CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2882  const RecordType *RT = Ty->getAs<RecordType>();
2883  llvm::SmallPtrSet<MemberKind*, 1> Results;
2884
2885  if (!RT)
2886    return Results;
2887  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2888  if (!RD)
2889    return Results;
2890
2891  LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2892                 Sema::LookupMemberName);
2893
2894  // We just need to include all members of the right kind turned up by the
2895  // filter, at this point.
2896  if (S.LookupQualifiedName(R, RT->getDecl()))
2897    for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2898      NamedDecl *decl = (*I)->getUnderlyingDecl();
2899      if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2900        Results.insert(FK);
2901    }
2902  return Results;
2903}
2904
2905// Check if a (w)string was passed when a (w)char* was needed, and offer a
2906// better diagnostic if so. AT is assumed to be valid.
2907// Returns true when a c_str() conversion method is found.
2908bool CheckPrintfHandler::checkForCStrMembers(
2909    const analyze_printf::ArgType &AT, const Expr *E,
2910    const CharSourceRange &CSR) {
2911  typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2912
2913  MethodSet Results =
2914      CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2915
2916  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2917       MI != ME; ++MI) {
2918    const CXXMethodDecl *Method = *MI;
2919    if (Method->getNumParams() == 0 &&
2920          AT.matchesType(S.Context, Method->getResultType())) {
2921      // FIXME: Suggest parens if the expression needs them.
2922      SourceLocation EndLoc =
2923          S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2924      S.Diag(E->getLocStart(), diag::note_printf_c_str)
2925          << "c_str()"
2926          << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2927      return true;
2928    }
2929  }
2930
2931  return false;
2932}
2933
2934bool
2935CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2936                                            &FS,
2937                                          const char *startSpecifier,
2938                                          unsigned specifierLen) {
2939
2940  using namespace analyze_format_string;
2941  using namespace analyze_printf;
2942  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2943
2944  if (FS.consumesDataArgument()) {
2945    if (atFirstArg) {
2946        atFirstArg = false;
2947        usesPositionalArgs = FS.usesPositionalArg();
2948    }
2949    else if (usesPositionalArgs != FS.usesPositionalArg()) {
2950      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2951                                        startSpecifier, specifierLen);
2952      return false;
2953    }
2954  }
2955
2956  // First check if the field width, precision, and conversion specifier
2957  // have matching data arguments.
2958  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2959                    startSpecifier, specifierLen)) {
2960    return false;
2961  }
2962
2963  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2964                    startSpecifier, specifierLen)) {
2965    return false;
2966  }
2967
2968  if (!CS.consumesDataArgument()) {
2969    // FIXME: Technically specifying a precision or field width here
2970    // makes no sense.  Worth issuing a warning at some point.
2971    return true;
2972  }
2973
2974  // Consume the argument.
2975  unsigned argIndex = FS.getArgIndex();
2976  if (argIndex < NumDataArgs) {
2977    // The check to see if the argIndex is valid will come later.
2978    // We set the bit here because we may exit early from this
2979    // function if we encounter some other error.
2980    CoveredArgs.set(argIndex);
2981  }
2982
2983  // FreeBSD extensions
2984  if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
2985      CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
2986    // claim the second argument
2987    CoveredArgs.set(argIndex + 1);
2988
2989    // Now type check the data expression that matches the
2990    // format specifier.
2991    const Expr *Ex = getDataArg(argIndex);
2992    const analyze_printf::ArgType &AT =
2993      (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
2994        ArgType(S.Context.IntTy) : ArgType::CStrTy;
2995    if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
2996      S.Diag(getLocationOfByte(CS.getStart()),
2997             diag::warn_printf_conversion_argument_type_mismatch)
2998        << AT.getRepresentativeType(S.Context) << Ex->getType()
2999        << getSpecifierRange(startSpecifier, specifierLen)
3000        << Ex->getSourceRange();
3001
3002    // Now type check the data expression that matches the
3003    // format specifier.
3004    Ex = getDataArg(argIndex + 1);
3005    const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3006    if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3007      S.Diag(getLocationOfByte(CS.getStart()),
3008             diag::warn_printf_conversion_argument_type_mismatch)
3009        << AT2.getRepresentativeType(S.Context) << Ex->getType()
3010        << getSpecifierRange(startSpecifier, specifierLen)
3011        << Ex->getSourceRange();
3012
3013     return true;
3014  }
3015  // END OF FREEBSD EXTENSIONS
3016
3017  // Check for using an Objective-C specific conversion specifier
3018  // in a non-ObjC literal.
3019  if (!ObjCContext && CS.isObjCArg()) {
3020    return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3021                                                  specifierLen);
3022  }
3023
3024  // Check for invalid use of field width
3025  if (!FS.hasValidFieldWidth()) {
3026    HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3027        startSpecifier, specifierLen);
3028  }
3029
3030  // Check for invalid use of precision
3031  if (!FS.hasValidPrecision()) {
3032    HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3033        startSpecifier, specifierLen);
3034  }
3035
3036  // Check each flag does not conflict with any other component.
3037  if (!FS.hasValidThousandsGroupingPrefix())
3038    HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3039  if (!FS.hasValidLeadingZeros())
3040    HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3041  if (!FS.hasValidPlusPrefix())
3042    HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3043  if (!FS.hasValidSpacePrefix())
3044    HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3045  if (!FS.hasValidAlternativeForm())
3046    HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3047  if (!FS.hasValidLeftJustified())
3048    HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3049
3050  // Check that flags are not ignored by another flag
3051  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3052    HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3053        startSpecifier, specifierLen);
3054  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3055    HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3056            startSpecifier, specifierLen);
3057
3058  // Check the length modifier is valid with the given conversion specifier.
3059  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3060    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3061                                diag::warn_format_nonsensical_length);
3062  else if (!FS.hasStandardLengthModifier())
3063    HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3064  else if (!FS.hasStandardLengthConversionCombination())
3065    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3066                                diag::warn_format_non_standard_conversion_spec);
3067
3068  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3069    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3070
3071  // The remaining checks depend on the data arguments.
3072  if (HasVAListArg)
3073    return true;
3074
3075  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3076    return false;
3077
3078  const Expr *Arg = getDataArg(argIndex);
3079  if (!Arg)
3080    return true;
3081
3082  return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3083}
3084
3085static bool requiresParensToAddCast(const Expr *E) {
3086  // FIXME: We should have a general way to reason about operator
3087  // precedence and whether parens are actually needed here.
3088  // Take care of a few common cases where they aren't.
3089  const Expr *Inside = E->IgnoreImpCasts();
3090  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3091    Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3092
3093  switch (Inside->getStmtClass()) {
3094  case Stmt::ArraySubscriptExprClass:
3095  case Stmt::CallExprClass:
3096  case Stmt::CharacterLiteralClass:
3097  case Stmt::CXXBoolLiteralExprClass:
3098  case Stmt::DeclRefExprClass:
3099  case Stmt::FloatingLiteralClass:
3100  case Stmt::IntegerLiteralClass:
3101  case Stmt::MemberExprClass:
3102  case Stmt::ObjCArrayLiteralClass:
3103  case Stmt::ObjCBoolLiteralExprClass:
3104  case Stmt::ObjCBoxedExprClass:
3105  case Stmt::ObjCDictionaryLiteralClass:
3106  case Stmt::ObjCEncodeExprClass:
3107  case Stmt::ObjCIvarRefExprClass:
3108  case Stmt::ObjCMessageExprClass:
3109  case Stmt::ObjCPropertyRefExprClass:
3110  case Stmt::ObjCStringLiteralClass:
3111  case Stmt::ObjCSubscriptRefExprClass:
3112  case Stmt::ParenExprClass:
3113  case Stmt::StringLiteralClass:
3114  case Stmt::UnaryOperatorClass:
3115    return false;
3116  default:
3117    return true;
3118  }
3119}
3120
3121bool
3122CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3123                                    const char *StartSpecifier,
3124                                    unsigned SpecifierLen,
3125                                    const Expr *E) {
3126  using namespace analyze_format_string;
3127  using namespace analyze_printf;
3128  // Now type check the data expression that matches the
3129  // format specifier.
3130  const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3131                                                    ObjCContext);
3132  if (!AT.isValid())
3133    return true;
3134
3135  QualType ExprTy = E->getType();
3136  while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3137    ExprTy = TET->getUnderlyingExpr()->getType();
3138  }
3139
3140  if (AT.matchesType(S.Context, ExprTy))
3141    return true;
3142
3143  // Look through argument promotions for our error message's reported type.
3144  // This includes the integral and floating promotions, but excludes array
3145  // and function pointer decay; seeing that an argument intended to be a
3146  // string has type 'char [6]' is probably more confusing than 'char *'.
3147  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3148    if (ICE->getCastKind() == CK_IntegralCast ||
3149        ICE->getCastKind() == CK_FloatingCast) {
3150      E = ICE->getSubExpr();
3151      ExprTy = E->getType();
3152
3153      // Check if we didn't match because of an implicit cast from a 'char'
3154      // or 'short' to an 'int'.  This is done because printf is a varargs
3155      // function.
3156      if (ICE->getType() == S.Context.IntTy ||
3157          ICE->getType() == S.Context.UnsignedIntTy) {
3158        // All further checking is done on the subexpression.
3159        if (AT.matchesType(S.Context, ExprTy))
3160          return true;
3161      }
3162    }
3163  } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3164    // Special case for 'a', which has type 'int' in C.
3165    // Note, however, that we do /not/ want to treat multibyte constants like
3166    // 'MooV' as characters! This form is deprecated but still exists.
3167    if (ExprTy == S.Context.IntTy)
3168      if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3169        ExprTy = S.Context.CharTy;
3170  }
3171
3172  // %C in an Objective-C context prints a unichar, not a wchar_t.
3173  // If the argument is an integer of some kind, believe the %C and suggest
3174  // a cast instead of changing the conversion specifier.
3175  QualType IntendedTy = ExprTy;
3176  if (ObjCContext &&
3177      FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3178    if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3179        !ExprTy->isCharType()) {
3180      // 'unichar' is defined as a typedef of unsigned short, but we should
3181      // prefer using the typedef if it is visible.
3182      IntendedTy = S.Context.UnsignedShortTy;
3183
3184      // While we are here, check if the value is an IntegerLiteral that happens
3185      // to be within the valid range.
3186      if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3187        const llvm::APInt &V = IL->getValue();
3188        if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3189          return true;
3190      }
3191
3192      LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3193                          Sema::LookupOrdinaryName);
3194      if (S.LookupName(Result, S.getCurScope())) {
3195        NamedDecl *ND = Result.getFoundDecl();
3196        if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3197          if (TD->getUnderlyingType() == IntendedTy)
3198            IntendedTy = S.Context.getTypedefType(TD);
3199      }
3200    }
3201  }
3202
3203  // Special-case some of Darwin's platform-independence types by suggesting
3204  // casts to primitive types that are known to be large enough.
3205  bool ShouldNotPrintDirectly = false;
3206  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3207    // Use a 'while' to peel off layers of typedefs.
3208    QualType TyTy = IntendedTy;
3209    while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3210      StringRef Name = UserTy->getDecl()->getName();
3211      QualType CastTy = llvm::StringSwitch<QualType>(Name)
3212        .Case("NSInteger", S.Context.LongTy)
3213        .Case("NSUInteger", S.Context.UnsignedLongTy)
3214        .Case("SInt32", S.Context.IntTy)
3215        .Case("UInt32", S.Context.UnsignedIntTy)
3216        .Default(QualType());
3217
3218      if (!CastTy.isNull()) {
3219        ShouldNotPrintDirectly = true;
3220        IntendedTy = CastTy;
3221        break;
3222      }
3223      TyTy = UserTy->desugar();
3224    }
3225  }
3226
3227  // We may be able to offer a FixItHint if it is a supported type.
3228  PrintfSpecifier fixedFS = FS;
3229  bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3230                                 S.Context, ObjCContext);
3231
3232  if (success) {
3233    // Get the fix string from the fixed format specifier
3234    SmallString<16> buf;
3235    llvm::raw_svector_ostream os(buf);
3236    fixedFS.toString(os);
3237
3238    CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3239
3240    if (IntendedTy == ExprTy) {
3241      // In this case, the specifier is wrong and should be changed to match
3242      // the argument.
3243      EmitFormatDiagnostic(
3244        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3245          << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3246          << E->getSourceRange(),
3247        E->getLocStart(),
3248        /*IsStringLocation*/false,
3249        SpecRange,
3250        FixItHint::CreateReplacement(SpecRange, os.str()));
3251
3252    } else {
3253      // The canonical type for formatting this value is different from the
3254      // actual type of the expression. (This occurs, for example, with Darwin's
3255      // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3256      // should be printed as 'long' for 64-bit compatibility.)
3257      // Rather than emitting a normal format/argument mismatch, we want to
3258      // add a cast to the recommended type (and correct the format string
3259      // if necessary).
3260      SmallString<16> CastBuf;
3261      llvm::raw_svector_ostream CastFix(CastBuf);
3262      CastFix << "(";
3263      IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3264      CastFix << ")";
3265
3266      SmallVector<FixItHint,4> Hints;
3267      if (!AT.matchesType(S.Context, IntendedTy))
3268        Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3269
3270      if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3271        // If there's already a cast present, just replace it.
3272        SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3273        Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3274
3275      } else if (!requiresParensToAddCast(E)) {
3276        // If the expression has high enough precedence,
3277        // just write the C-style cast.
3278        Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3279                                                   CastFix.str()));
3280      } else {
3281        // Otherwise, add parens around the expression as well as the cast.
3282        CastFix << "(";
3283        Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3284                                                   CastFix.str()));
3285
3286        SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3287        Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3288      }
3289
3290      if (ShouldNotPrintDirectly) {
3291        // The expression has a type that should not be printed directly.
3292        // We extract the name from the typedef because we don't want to show
3293        // the underlying type in the diagnostic.
3294        StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
3295
3296        EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3297                               << Name << IntendedTy
3298                               << E->getSourceRange(),
3299                             E->getLocStart(), /*IsStringLocation=*/false,
3300                             SpecRange, Hints);
3301      } else {
3302        // In this case, the expression could be printed using a different
3303        // specifier, but we've decided that the specifier is probably correct
3304        // and we should cast instead. Just use the normal warning message.
3305        EmitFormatDiagnostic(
3306          S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3307            << AT.getRepresentativeTypeName(S.Context) << ExprTy
3308            << E->getSourceRange(),
3309          E->getLocStart(), /*IsStringLocation*/false,
3310          SpecRange, Hints);
3311      }
3312    }
3313  } else {
3314    const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3315                                                   SpecifierLen);
3316    // Since the warning for passing non-POD types to variadic functions
3317    // was deferred until now, we emit a warning for non-POD
3318    // arguments here.
3319    switch (S.isValidVarArgType(ExprTy)) {
3320    case Sema::VAK_Valid:
3321    case Sema::VAK_ValidInCXX11:
3322      EmitFormatDiagnostic(
3323        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3324          << AT.getRepresentativeTypeName(S.Context) << ExprTy
3325          << CSR
3326          << E->getSourceRange(),
3327        E->getLocStart(), /*IsStringLocation*/false, CSR);
3328      break;
3329
3330    case Sema::VAK_Undefined:
3331      EmitFormatDiagnostic(
3332        S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3333          << S.getLangOpts().CPlusPlus11
3334          << ExprTy
3335          << CallType
3336          << AT.getRepresentativeTypeName(S.Context)
3337          << CSR
3338          << E->getSourceRange(),
3339        E->getLocStart(), /*IsStringLocation*/false, CSR);
3340      checkForCStrMembers(AT, E, CSR);
3341      break;
3342
3343    case Sema::VAK_Invalid:
3344      if (ExprTy->isObjCObjectType())
3345        EmitFormatDiagnostic(
3346          S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3347            << S.getLangOpts().CPlusPlus11
3348            << ExprTy
3349            << CallType
3350            << AT.getRepresentativeTypeName(S.Context)
3351            << CSR
3352            << E->getSourceRange(),
3353          E->getLocStart(), /*IsStringLocation*/false, CSR);
3354      else
3355        // FIXME: If this is an initializer list, suggest removing the braces
3356        // or inserting a cast to the target type.
3357        S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3358          << isa<InitListExpr>(E) << ExprTy << CallType
3359          << AT.getRepresentativeTypeName(S.Context)
3360          << E->getSourceRange();
3361      break;
3362    }
3363
3364    assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3365           "format string specifier index out of range");
3366    CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3367  }
3368
3369  return true;
3370}
3371
3372//===--- CHECK: Scanf format string checking ------------------------------===//
3373
3374namespace {
3375class CheckScanfHandler : public CheckFormatHandler {
3376public:
3377  CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3378                    const Expr *origFormatExpr, unsigned firstDataArg,
3379                    unsigned numDataArgs, const char *beg, bool hasVAListArg,
3380                    ArrayRef<const Expr *> Args,
3381                    unsigned formatIdx, bool inFunctionCall,
3382                    Sema::VariadicCallType CallType,
3383                    llvm::SmallBitVector &CheckedVarArgs)
3384    : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3385                         numDataArgs, beg, hasVAListArg,
3386                         Args, formatIdx, inFunctionCall, CallType,
3387                         CheckedVarArgs)
3388  {}
3389
3390  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3391                            const char *startSpecifier,
3392                            unsigned specifierLen);
3393
3394  bool HandleInvalidScanfConversionSpecifier(
3395          const analyze_scanf::ScanfSpecifier &FS,
3396          const char *startSpecifier,
3397          unsigned specifierLen);
3398
3399  void HandleIncompleteScanList(const char *start, const char *end);
3400};
3401}
3402
3403void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3404                                                 const char *end) {
3405  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3406                       getLocationOfByte(end), /*IsStringLocation*/true,
3407                       getSpecifierRange(start, end - start));
3408}
3409
3410bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3411                                        const analyze_scanf::ScanfSpecifier &FS,
3412                                        const char *startSpecifier,
3413                                        unsigned specifierLen) {
3414
3415  const analyze_scanf::ScanfConversionSpecifier &CS =
3416    FS.getConversionSpecifier();
3417
3418  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3419                                          getLocationOfByte(CS.getStart()),
3420                                          startSpecifier, specifierLen,
3421                                          CS.getStart(), CS.getLength());
3422}
3423
3424bool CheckScanfHandler::HandleScanfSpecifier(
3425                                       const analyze_scanf::ScanfSpecifier &FS,
3426                                       const char *startSpecifier,
3427                                       unsigned specifierLen) {
3428
3429  using namespace analyze_scanf;
3430  using namespace analyze_format_string;
3431
3432  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3433
3434  // Handle case where '%' and '*' don't consume an argument.  These shouldn't
3435  // be used to decide if we are using positional arguments consistently.
3436  if (FS.consumesDataArgument()) {
3437    if (atFirstArg) {
3438      atFirstArg = false;
3439      usesPositionalArgs = FS.usesPositionalArg();
3440    }
3441    else if (usesPositionalArgs != FS.usesPositionalArg()) {
3442      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3443                                        startSpecifier, specifierLen);
3444      return false;
3445    }
3446  }
3447
3448  // Check if the field with is non-zero.
3449  const OptionalAmount &Amt = FS.getFieldWidth();
3450  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3451    if (Amt.getConstantAmount() == 0) {
3452      const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3453                                                   Amt.getConstantLength());
3454      EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3455                           getLocationOfByte(Amt.getStart()),
3456                           /*IsStringLocation*/true, R,
3457                           FixItHint::CreateRemoval(R));
3458    }
3459  }
3460
3461  if (!FS.consumesDataArgument()) {
3462    // FIXME: Technically specifying a precision or field width here
3463    // makes no sense.  Worth issuing a warning at some point.
3464    return true;
3465  }
3466
3467  // Consume the argument.
3468  unsigned argIndex = FS.getArgIndex();
3469  if (argIndex < NumDataArgs) {
3470      // The check to see if the argIndex is valid will come later.
3471      // We set the bit here because we may exit early from this
3472      // function if we encounter some other error.
3473    CoveredArgs.set(argIndex);
3474  }
3475
3476  // Check the length modifier is valid with the given conversion specifier.
3477  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3478    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3479                                diag::warn_format_nonsensical_length);
3480  else if (!FS.hasStandardLengthModifier())
3481    HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3482  else if (!FS.hasStandardLengthConversionCombination())
3483    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3484                                diag::warn_format_non_standard_conversion_spec);
3485
3486  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3487    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3488
3489  // The remaining checks depend on the data arguments.
3490  if (HasVAListArg)
3491    return true;
3492
3493  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3494    return false;
3495
3496  // Check that the argument type matches the format specifier.
3497  const Expr *Ex = getDataArg(argIndex);
3498  if (!Ex)
3499    return true;
3500
3501  const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3502  if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3503    ScanfSpecifier fixedFS = FS;
3504    bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
3505                                   S.Context);
3506
3507    if (success) {
3508      // Get the fix string from the fixed format specifier.
3509      SmallString<128> buf;
3510      llvm::raw_svector_ostream os(buf);
3511      fixedFS.toString(os);
3512
3513      EmitFormatDiagnostic(
3514        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3515          << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3516          << Ex->getSourceRange(),
3517        Ex->getLocStart(),
3518        /*IsStringLocation*/false,
3519        getSpecifierRange(startSpecifier, specifierLen),
3520        FixItHint::CreateReplacement(
3521          getSpecifierRange(startSpecifier, specifierLen),
3522          os.str()));
3523    } else {
3524      EmitFormatDiagnostic(
3525        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3526          << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3527          << Ex->getSourceRange(),
3528        Ex->getLocStart(),
3529        /*IsStringLocation*/false,
3530        getSpecifierRange(startSpecifier, specifierLen));
3531    }
3532  }
3533
3534  return true;
3535}
3536
3537void Sema::CheckFormatString(const StringLiteral *FExpr,
3538                             const Expr *OrigFormatExpr,
3539                             ArrayRef<const Expr *> Args,
3540                             bool HasVAListArg, unsigned format_idx,
3541                             unsigned firstDataArg, FormatStringType Type,
3542                             bool inFunctionCall, VariadicCallType CallType,
3543                             llvm::SmallBitVector &CheckedVarArgs) {
3544
3545  // CHECK: is the format string a wide literal?
3546  if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3547    CheckFormatHandler::EmitFormatDiagnostic(
3548      *this, inFunctionCall, Args[format_idx],
3549      PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3550      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3551    return;
3552  }
3553
3554  // Str - The format string.  NOTE: this is NOT null-terminated!
3555  StringRef StrRef = FExpr->getString();
3556  const char *Str = StrRef.data();
3557  unsigned StrLen = StrRef.size();
3558  const unsigned numDataArgs = Args.size() - firstDataArg;
3559
3560  // CHECK: empty format string?
3561  if (StrLen == 0 && numDataArgs > 0) {
3562    CheckFormatHandler::EmitFormatDiagnostic(
3563      *this, inFunctionCall, Args[format_idx],
3564      PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3565      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3566    return;
3567  }
3568
3569  if (Type == FST_Printf || Type == FST_NSString) {
3570    CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3571                         numDataArgs, (Type == FST_NSString),
3572                         Str, HasVAListArg, Args, format_idx,
3573                         inFunctionCall, CallType, CheckedVarArgs);
3574
3575    if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3576                                                  getLangOpts(),
3577                                                  Context.getTargetInfo()))
3578      H.DoneProcessing();
3579  } else if (Type == FST_Scanf) {
3580    CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3581                        Str, HasVAListArg, Args, format_idx,
3582                        inFunctionCall, CallType, CheckedVarArgs);
3583
3584    if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3585                                                 getLangOpts(),
3586                                                 Context.getTargetInfo()))
3587      H.DoneProcessing();
3588  } // TODO: handle other formats
3589}
3590
3591//===--- CHECK: Standard memory functions ---------------------------------===//
3592
3593/// \brief Determine whether the given type is a dynamic class type (e.g.,
3594/// whether it has a vtable).
3595static bool isDynamicClassType(QualType T) {
3596  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3597    if (CXXRecordDecl *Definition = Record->getDefinition())
3598      if (Definition->isDynamicClass())
3599        return true;
3600
3601  return false;
3602}
3603
3604/// \brief If E is a sizeof expression, returns its argument expression,
3605/// otherwise returns NULL.
3606static const Expr *getSizeOfExprArg(const Expr* E) {
3607  if (const UnaryExprOrTypeTraitExpr *SizeOf =
3608      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3609    if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3610      return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
3611
3612  return 0;
3613}
3614
3615/// \brief If E is a sizeof expression, returns its argument type.
3616static QualType getSizeOfArgType(const Expr* E) {
3617  if (const UnaryExprOrTypeTraitExpr *SizeOf =
3618      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3619    if (SizeOf->getKind() == clang::UETT_SizeOf)
3620      return SizeOf->getTypeOfArgument();
3621
3622  return QualType();
3623}
3624
3625/// \brief Check for dangerous or invalid arguments to memset().
3626///
3627/// This issues warnings on known problematic, dangerous or unspecified
3628/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3629/// function calls.
3630///
3631/// \param Call The call expression to diagnose.
3632void Sema::CheckMemaccessArguments(const CallExpr *Call,
3633                                   unsigned BId,
3634                                   IdentifierInfo *FnName) {
3635  assert(BId != 0);
3636
3637  // It is possible to have a non-standard definition of memset.  Validate
3638  // we have enough arguments, and if not, abort further checking.
3639  unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
3640  if (Call->getNumArgs() < ExpectedNumArgs)
3641    return;
3642
3643  unsigned LastArg = (BId == Builtin::BImemset ||
3644                      BId == Builtin::BIstrndup ? 1 : 2);
3645  unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
3646  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
3647
3648  // We have special checking when the length is a sizeof expression.
3649  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3650  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3651  llvm::FoldingSetNodeID SizeOfArgID;
3652
3653  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3654    const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
3655    SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
3656
3657    QualType DestTy = Dest->getType();
3658    if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3659      QualType PointeeTy = DestPtrTy->getPointeeType();
3660
3661      // Never warn about void type pointers. This can be used to suppress
3662      // false positives.
3663      if (PointeeTy->isVoidType())
3664        continue;
3665
3666      // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3667      // actually comparing the expressions for equality. Because computing the
3668      // expression IDs can be expensive, we only do this if the diagnostic is
3669      // enabled.
3670      if (SizeOfArg &&
3671          Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3672                                   SizeOfArg->getExprLoc())) {
3673        // We only compute IDs for expressions if the warning is enabled, and
3674        // cache the sizeof arg's ID.
3675        if (SizeOfArgID == llvm::FoldingSetNodeID())
3676          SizeOfArg->Profile(SizeOfArgID, Context, true);
3677        llvm::FoldingSetNodeID DestID;
3678        Dest->Profile(DestID, Context, true);
3679        if (DestID == SizeOfArgID) {
3680          // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3681          //       over sizeof(src) as well.
3682          unsigned ActionIdx = 0; // Default is to suggest dereferencing.
3683          StringRef ReadableName = FnName->getName();
3684
3685          if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
3686            if (UnaryOp->getOpcode() == UO_AddrOf)
3687              ActionIdx = 1; // If its an address-of operator, just remove it.
3688          if (!PointeeTy->isIncompleteType() &&
3689              (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
3690            ActionIdx = 2; // If the pointee's size is sizeof(char),
3691                           // suggest an explicit length.
3692
3693          // If the function is defined as a builtin macro, do not show macro
3694          // expansion.
3695          SourceLocation SL = SizeOfArg->getExprLoc();
3696          SourceRange DSR = Dest->getSourceRange();
3697          SourceRange SSR = SizeOfArg->getSourceRange();
3698          SourceManager &SM  = PP.getSourceManager();
3699
3700          if (SM.isMacroArgExpansion(SL)) {
3701            ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3702            SL = SM.getSpellingLoc(SL);
3703            DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3704                             SM.getSpellingLoc(DSR.getEnd()));
3705            SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3706                             SM.getSpellingLoc(SSR.getEnd()));
3707          }
3708
3709          DiagRuntimeBehavior(SL, SizeOfArg,
3710                              PDiag(diag::warn_sizeof_pointer_expr_memaccess)
3711                                << ReadableName
3712                                << PointeeTy
3713                                << DestTy
3714                                << DSR
3715                                << SSR);
3716          DiagRuntimeBehavior(SL, SizeOfArg,
3717                         PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3718                                << ActionIdx
3719                                << SSR);
3720
3721          break;
3722        }
3723      }
3724
3725      // Also check for cases where the sizeof argument is the exact same
3726      // type as the memory argument, and where it points to a user-defined
3727      // record type.
3728      if (SizeOfArgTy != QualType()) {
3729        if (PointeeTy->isRecordType() &&
3730            Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3731          DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3732                              PDiag(diag::warn_sizeof_pointer_type_memaccess)
3733                                << FnName << SizeOfArgTy << ArgIdx
3734                                << PointeeTy << Dest->getSourceRange()
3735                                << LenExpr->getSourceRange());
3736          break;
3737        }
3738      }
3739
3740      // Always complain about dynamic classes.
3741      if (isDynamicClassType(PointeeTy)) {
3742
3743        unsigned OperationType = 0;
3744        // "overwritten" if we're warning about the destination for any call
3745        // but memcmp; otherwise a verb appropriate to the call.
3746        if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3747          if (BId == Builtin::BImemcpy)
3748            OperationType = 1;
3749          else if(BId == Builtin::BImemmove)
3750            OperationType = 2;
3751          else if (BId == Builtin::BImemcmp)
3752            OperationType = 3;
3753        }
3754
3755        DiagRuntimeBehavior(
3756          Dest->getExprLoc(), Dest,
3757          PDiag(diag::warn_dyn_class_memaccess)
3758            << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
3759            << FnName << PointeeTy
3760            << OperationType
3761            << Call->getCallee()->getSourceRange());
3762      } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3763               BId != Builtin::BImemset)
3764        DiagRuntimeBehavior(
3765          Dest->getExprLoc(), Dest,
3766          PDiag(diag::warn_arc_object_memaccess)
3767            << ArgIdx << FnName << PointeeTy
3768            << Call->getCallee()->getSourceRange());
3769      else
3770        continue;
3771
3772      DiagRuntimeBehavior(
3773        Dest->getExprLoc(), Dest,
3774        PDiag(diag::note_bad_memaccess_silence)
3775          << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3776      break;
3777    }
3778  }
3779}
3780
3781// A little helper routine: ignore addition and subtraction of integer literals.
3782// This intentionally does not ignore all integer constant expressions because
3783// we don't want to remove sizeof().
3784static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3785  Ex = Ex->IgnoreParenCasts();
3786
3787  for (;;) {
3788    const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3789    if (!BO || !BO->isAdditiveOp())
3790      break;
3791
3792    const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3793    const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3794
3795    if (isa<IntegerLiteral>(RHS))
3796      Ex = LHS;
3797    else if (isa<IntegerLiteral>(LHS))
3798      Ex = RHS;
3799    else
3800      break;
3801  }
3802
3803  return Ex;
3804}
3805
3806static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3807                                                      ASTContext &Context) {
3808  // Only handle constant-sized or VLAs, but not flexible members.
3809  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3810    // Only issue the FIXIT for arrays of size > 1.
3811    if (CAT->getSize().getSExtValue() <= 1)
3812      return false;
3813  } else if (!Ty->isVariableArrayType()) {
3814    return false;
3815  }
3816  return true;
3817}
3818
3819// Warn if the user has made the 'size' argument to strlcpy or strlcat
3820// be the size of the source, instead of the destination.
3821void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3822                                    IdentifierInfo *FnName) {
3823
3824  // Don't crash if the user has the wrong number of arguments
3825  if (Call->getNumArgs() != 3)
3826    return;
3827
3828  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3829  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3830  const Expr *CompareWithSrc = NULL;
3831
3832  // Look for 'strlcpy(dst, x, sizeof(x))'
3833  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3834    CompareWithSrc = Ex;
3835  else {
3836    // Look for 'strlcpy(dst, x, strlen(x))'
3837    if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
3838      if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
3839          && SizeCall->getNumArgs() == 1)
3840        CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3841    }
3842  }
3843
3844  if (!CompareWithSrc)
3845    return;
3846
3847  // Determine if the argument to sizeof/strlen is equal to the source
3848  // argument.  In principle there's all kinds of things you could do
3849  // here, for instance creating an == expression and evaluating it with
3850  // EvaluateAsBooleanCondition, but this uses a more direct technique:
3851  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3852  if (!SrcArgDRE)
3853    return;
3854
3855  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3856  if (!CompareWithSrcDRE ||
3857      SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3858    return;
3859
3860  const Expr *OriginalSizeArg = Call->getArg(2);
3861  Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3862    << OriginalSizeArg->getSourceRange() << FnName;
3863
3864  // Output a FIXIT hint if the destination is an array (rather than a
3865  // pointer to an array).  This could be enhanced to handle some
3866  // pointers if we know the actual size, like if DstArg is 'array+2'
3867  // we could say 'sizeof(array)-2'.
3868  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
3869  if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
3870    return;
3871
3872  SmallString<128> sizeString;
3873  llvm::raw_svector_ostream OS(sizeString);
3874  OS << "sizeof(";
3875  DstArg->printPretty(OS, 0, getPrintingPolicy());
3876  OS << ")";
3877
3878  Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3879    << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3880                                    OS.str());
3881}
3882
3883/// Check if two expressions refer to the same declaration.
3884static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3885  if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3886    if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3887      return D1->getDecl() == D2->getDecl();
3888  return false;
3889}
3890
3891static const Expr *getStrlenExprArg(const Expr *E) {
3892  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3893    const FunctionDecl *FD = CE->getDirectCallee();
3894    if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3895      return 0;
3896    return CE->getArg(0)->IgnoreParenCasts();
3897  }
3898  return 0;
3899}
3900
3901// Warn on anti-patterns as the 'size' argument to strncat.
3902// The correct size argument should look like following:
3903//   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3904void Sema::CheckStrncatArguments(const CallExpr *CE,
3905                                 IdentifierInfo *FnName) {
3906  // Don't crash if the user has the wrong number of arguments.
3907  if (CE->getNumArgs() < 3)
3908    return;
3909  const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3910  const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3911  const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3912
3913  // Identify common expressions, which are wrongly used as the size argument
3914  // to strncat and may lead to buffer overflows.
3915  unsigned PatternType = 0;
3916  if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3917    // - sizeof(dst)
3918    if (referToTheSameDecl(SizeOfArg, DstArg))
3919      PatternType = 1;
3920    // - sizeof(src)
3921    else if (referToTheSameDecl(SizeOfArg, SrcArg))
3922      PatternType = 2;
3923  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3924    if (BE->getOpcode() == BO_Sub) {
3925      const Expr *L = BE->getLHS()->IgnoreParenCasts();
3926      const Expr *R = BE->getRHS()->IgnoreParenCasts();
3927      // - sizeof(dst) - strlen(dst)
3928      if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3929          referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3930        PatternType = 1;
3931      // - sizeof(src) - (anything)
3932      else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3933        PatternType = 2;
3934    }
3935  }
3936
3937  if (PatternType == 0)
3938    return;
3939
3940  // Generate the diagnostic.
3941  SourceLocation SL = LenArg->getLocStart();
3942  SourceRange SR = LenArg->getSourceRange();
3943  SourceManager &SM  = PP.getSourceManager();
3944
3945  // If the function is defined as a builtin macro, do not show macro expansion.
3946  if (SM.isMacroArgExpansion(SL)) {
3947    SL = SM.getSpellingLoc(SL);
3948    SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3949                     SM.getSpellingLoc(SR.getEnd()));
3950  }
3951
3952  // Check if the destination is an array (rather than a pointer to an array).
3953  QualType DstTy = DstArg->getType();
3954  bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3955                                                                    Context);
3956  if (!isKnownSizeArray) {
3957    if (PatternType == 1)
3958      Diag(SL, diag::warn_strncat_wrong_size) << SR;
3959    else
3960      Diag(SL, diag::warn_strncat_src_size) << SR;
3961    return;
3962  }
3963
3964  if (PatternType == 1)
3965    Diag(SL, diag::warn_strncat_large_size) << SR;
3966  else
3967    Diag(SL, diag::warn_strncat_src_size) << SR;
3968
3969  SmallString<128> sizeString;
3970  llvm::raw_svector_ostream OS(sizeString);
3971  OS << "sizeof(";
3972  DstArg->printPretty(OS, 0, getPrintingPolicy());
3973  OS << ") - ";
3974  OS << "strlen(";
3975  DstArg->printPretty(OS, 0, getPrintingPolicy());
3976  OS << ") - 1";
3977
3978  Diag(SL, diag::note_strncat_wrong_size)
3979    << FixItHint::CreateReplacement(SR, OS.str());
3980}
3981
3982//===--- CHECK: Return Address of Stack Variable --------------------------===//
3983
3984static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3985                     Decl *ParentDecl);
3986static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3987                      Decl *ParentDecl);
3988
3989/// CheckReturnStackAddr - Check if a return statement returns the address
3990///   of a stack variable.
3991void
3992Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3993                           SourceLocation ReturnLoc) {
3994
3995  Expr *stackE = 0;
3996  SmallVector<DeclRefExpr *, 8> refVars;
3997
3998  // Perform checking for returned stack addresses, local blocks,
3999  // label addresses or references to temporaries.
4000  if (lhsType->isPointerType() ||
4001      (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4002    stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
4003  } else if (lhsType->isReferenceType()) {
4004    stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
4005  }
4006
4007  if (stackE == 0)
4008    return; // Nothing suspicious was found.
4009
4010  SourceLocation diagLoc;
4011  SourceRange diagRange;
4012  if (refVars.empty()) {
4013    diagLoc = stackE->getLocStart();
4014    diagRange = stackE->getSourceRange();
4015  } else {
4016    // We followed through a reference variable. 'stackE' contains the
4017    // problematic expression but we will warn at the return statement pointing
4018    // at the reference variable. We will later display the "trail" of
4019    // reference variables using notes.
4020    diagLoc = refVars[0]->getLocStart();
4021    diagRange = refVars[0]->getSourceRange();
4022  }
4023
4024  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4025    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4026                                             : diag::warn_ret_stack_addr)
4027     << DR->getDecl()->getDeclName() << diagRange;
4028  } else if (isa<BlockExpr>(stackE)) { // local block.
4029    Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4030  } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4031    Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4032  } else { // local temporary.
4033    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4034                                             : diag::warn_ret_local_temp_addr)
4035     << diagRange;
4036  }
4037
4038  // Display the "trail" of reference variables that we followed until we
4039  // found the problematic expression using notes.
4040  for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4041    VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4042    // If this var binds to another reference var, show the range of the next
4043    // var, otherwise the var binds to the problematic expression, in which case
4044    // show the range of the expression.
4045    SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4046                                  : stackE->getSourceRange();
4047    Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4048      << VD->getDeclName() << range;
4049  }
4050}
4051
4052/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4053///  check if the expression in a return statement evaluates to an address
4054///  to a location on the stack, a local block, an address of a label, or a
4055///  reference to local temporary. The recursion is used to traverse the
4056///  AST of the return expression, with recursion backtracking when we
4057///  encounter a subexpression that (1) clearly does not lead to one of the
4058///  above problematic expressions (2) is something we cannot determine leads to
4059///  a problematic expression based on such local checking.
4060///
4061///  Both EvalAddr and EvalVal follow through reference variables to evaluate
4062///  the expression that they point to. Such variables are added to the
4063///  'refVars' vector so that we know what the reference variable "trail" was.
4064///
4065///  EvalAddr processes expressions that are pointers that are used as
4066///  references (and not L-values).  EvalVal handles all other values.
4067///  At the base case of the recursion is a check for the above problematic
4068///  expressions.
4069///
4070///  This implementation handles:
4071///
4072///   * pointer-to-pointer casts
4073///   * implicit conversions from array references to pointers
4074///   * taking the address of fields
4075///   * arbitrary interplay between "&" and "*" operators
4076///   * pointer arithmetic from an address of a stack variable
4077///   * taking the address of an array element where the array is on the stack
4078static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4079                      Decl *ParentDecl) {
4080  if (E->isTypeDependent())
4081    return NULL;
4082
4083  // We should only be called for evaluating pointer expressions.
4084  assert((E->getType()->isAnyPointerType() ||
4085          E->getType()->isBlockPointerType() ||
4086          E->getType()->isObjCQualifiedIdType()) &&
4087         "EvalAddr only works on pointers");
4088
4089  E = E->IgnoreParens();
4090
4091  // Our "symbolic interpreter" is just a dispatch off the currently
4092  // viewed AST node.  We then recursively traverse the AST by calling
4093  // EvalAddr and EvalVal appropriately.
4094  switch (E->getStmtClass()) {
4095  case Stmt::DeclRefExprClass: {
4096    DeclRefExpr *DR = cast<DeclRefExpr>(E);
4097
4098    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4099      // If this is a reference variable, follow through to the expression that
4100      // it points to.
4101      if (V->hasLocalStorage() &&
4102          V->getType()->isReferenceType() && V->hasInit()) {
4103        // Add the reference variable to the "trail".
4104        refVars.push_back(DR);
4105        return EvalAddr(V->getInit(), refVars, ParentDecl);
4106      }
4107
4108    return NULL;
4109  }
4110
4111  case Stmt::UnaryOperatorClass: {
4112    // The only unary operator that make sense to handle here
4113    // is AddrOf.  All others don't make sense as pointers.
4114    UnaryOperator *U = cast<UnaryOperator>(E);
4115
4116    if (U->getOpcode() == UO_AddrOf)
4117      return EvalVal(U->getSubExpr(), refVars, ParentDecl);
4118    else
4119      return NULL;
4120  }
4121
4122  case Stmt::BinaryOperatorClass: {
4123    // Handle pointer arithmetic.  All other binary operators are not valid
4124    // in this context.
4125    BinaryOperator *B = cast<BinaryOperator>(E);
4126    BinaryOperatorKind op = B->getOpcode();
4127
4128    if (op != BO_Add && op != BO_Sub)
4129      return NULL;
4130
4131    Expr *Base = B->getLHS();
4132
4133    // Determine which argument is the real pointer base.  It could be
4134    // the RHS argument instead of the LHS.
4135    if (!Base->getType()->isPointerType()) Base = B->getRHS();
4136
4137    assert (Base->getType()->isPointerType());
4138    return EvalAddr(Base, refVars, ParentDecl);
4139  }
4140
4141  // For conditional operators we need to see if either the LHS or RHS are
4142  // valid DeclRefExpr*s.  If one of them is valid, we return it.
4143  case Stmt::ConditionalOperatorClass: {
4144    ConditionalOperator *C = cast<ConditionalOperator>(E);
4145
4146    // Handle the GNU extension for missing LHS.
4147    if (Expr *lhsExpr = C->getLHS()) {
4148    // In C++, we can have a throw-expression, which has 'void' type.
4149      if (!lhsExpr->getType()->isVoidType())
4150        if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
4151          return LHS;
4152    }
4153
4154    // In C++, we can have a throw-expression, which has 'void' type.
4155    if (C->getRHS()->getType()->isVoidType())
4156      return NULL;
4157
4158    return EvalAddr(C->getRHS(), refVars, ParentDecl);
4159  }
4160
4161  case Stmt::BlockExprClass:
4162    if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
4163      return E; // local block.
4164    return NULL;
4165
4166  case Stmt::AddrLabelExprClass:
4167    return E; // address of label.
4168
4169  case Stmt::ExprWithCleanupsClass:
4170    return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4171                    ParentDecl);
4172
4173  // For casts, we need to handle conversions from arrays to
4174  // pointer values, and pointer-to-pointer conversions.
4175  case Stmt::ImplicitCastExprClass:
4176  case Stmt::CStyleCastExprClass:
4177  case Stmt::CXXFunctionalCastExprClass:
4178  case Stmt::ObjCBridgedCastExprClass:
4179  case Stmt::CXXStaticCastExprClass:
4180  case Stmt::CXXDynamicCastExprClass:
4181  case Stmt::CXXConstCastExprClass:
4182  case Stmt::CXXReinterpretCastExprClass: {
4183    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4184    switch (cast<CastExpr>(E)->getCastKind()) {
4185    case CK_BitCast:
4186    case CK_LValueToRValue:
4187    case CK_NoOp:
4188    case CK_BaseToDerived:
4189    case CK_DerivedToBase:
4190    case CK_UncheckedDerivedToBase:
4191    case CK_Dynamic:
4192    case CK_CPointerToObjCPointerCast:
4193    case CK_BlockPointerToObjCPointerCast:
4194    case CK_AnyPointerToBlockPointerCast:
4195      return EvalAddr(SubExpr, refVars, ParentDecl);
4196
4197    case CK_ArrayToPointerDecay:
4198      return EvalVal(SubExpr, refVars, ParentDecl);
4199
4200    default:
4201      return 0;
4202    }
4203  }
4204
4205  case Stmt::MaterializeTemporaryExprClass:
4206    if (Expr *Result = EvalAddr(
4207                         cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4208                                refVars, ParentDecl))
4209      return Result;
4210
4211    return E;
4212
4213  // Everything else: we simply don't reason about them.
4214  default:
4215    return NULL;
4216  }
4217}
4218
4219
4220///  EvalVal - This function is complements EvalAddr in the mutual recursion.
4221///   See the comments for EvalAddr for more details.
4222static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4223                     Decl *ParentDecl) {
4224do {
4225  // We should only be called for evaluating non-pointer expressions, or
4226  // expressions with a pointer type that are not used as references but instead
4227  // are l-values (e.g., DeclRefExpr with a pointer type).
4228
4229  // Our "symbolic interpreter" is just a dispatch off the currently
4230  // viewed AST node.  We then recursively traverse the AST by calling
4231  // EvalAddr and EvalVal appropriately.
4232
4233  E = E->IgnoreParens();
4234  switch (E->getStmtClass()) {
4235  case Stmt::ImplicitCastExprClass: {
4236    ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
4237    if (IE->getValueKind() == VK_LValue) {
4238      E = IE->getSubExpr();
4239      continue;
4240    }
4241    return NULL;
4242  }
4243
4244  case Stmt::ExprWithCleanupsClass:
4245    return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
4246
4247  case Stmt::DeclRefExprClass: {
4248    // When we hit a DeclRefExpr we are looking at code that refers to a
4249    // variable's name. If it's not a reference variable we check if it has
4250    // local storage within the function, and if so, return the expression.
4251    DeclRefExpr *DR = cast<DeclRefExpr>(E);
4252
4253    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4254      // Check if it refers to itself, e.g. "int& i = i;".
4255      if (V == ParentDecl)
4256        return DR;
4257
4258      if (V->hasLocalStorage()) {
4259        if (!V->getType()->isReferenceType())
4260          return DR;
4261
4262        // Reference variable, follow through to the expression that
4263        // it points to.
4264        if (V->hasInit()) {
4265          // Add the reference variable to the "trail".
4266          refVars.push_back(DR);
4267          return EvalVal(V->getInit(), refVars, V);
4268        }
4269      }
4270    }
4271
4272    return NULL;
4273  }
4274
4275  case Stmt::UnaryOperatorClass: {
4276    // The only unary operator that make sense to handle here
4277    // is Deref.  All others don't resolve to a "name."  This includes
4278    // handling all sorts of rvalues passed to a unary operator.
4279    UnaryOperator *U = cast<UnaryOperator>(E);
4280
4281    if (U->getOpcode() == UO_Deref)
4282      return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
4283
4284    return NULL;
4285  }
4286
4287  case Stmt::ArraySubscriptExprClass: {
4288    // Array subscripts are potential references to data on the stack.  We
4289    // retrieve the DeclRefExpr* for the array variable if it indeed
4290    // has local storage.
4291    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
4292  }
4293
4294  case Stmt::ConditionalOperatorClass: {
4295    // For conditional operators we need to see if either the LHS or RHS are
4296    // non-NULL Expr's.  If one is non-NULL, we return it.
4297    ConditionalOperator *C = cast<ConditionalOperator>(E);
4298
4299    // Handle the GNU extension for missing LHS.
4300    if (Expr *lhsExpr = C->getLHS())
4301      if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
4302        return LHS;
4303
4304    return EvalVal(C->getRHS(), refVars, ParentDecl);
4305  }
4306
4307  // Accesses to members are potential references to data on the stack.
4308  case Stmt::MemberExprClass: {
4309    MemberExpr *M = cast<MemberExpr>(E);
4310
4311    // Check for indirect access.  We only want direct field accesses.
4312    if (M->isArrow())
4313      return NULL;
4314
4315    // Check whether the member type is itself a reference, in which case
4316    // we're not going to refer to the member, but to what the member refers to.
4317    if (M->getMemberDecl()->getType()->isReferenceType())
4318      return NULL;
4319
4320    return EvalVal(M->getBase(), refVars, ParentDecl);
4321  }
4322
4323  case Stmt::MaterializeTemporaryExprClass:
4324    if (Expr *Result = EvalVal(
4325                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4326                               refVars, ParentDecl))
4327      return Result;
4328
4329    return E;
4330
4331  default:
4332    // Check that we don't return or take the address of a reference to a
4333    // temporary. This is only useful in C++.
4334    if (!E->isTypeDependent() && E->isRValue())
4335      return E;
4336
4337    // Everything else: we simply don't reason about them.
4338    return NULL;
4339  }
4340} while (true);
4341}
4342
4343//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4344
4345/// Check for comparisons of floating point operands using != and ==.
4346/// Issue a warning if these are no self-comparisons, as they are not likely
4347/// to do what the programmer intended.
4348void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
4349  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4350  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
4351
4352  // Special case: check for x == x (which is OK).
4353  // Do not emit warnings for such cases.
4354  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4355    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4356      if (DRL->getDecl() == DRR->getDecl())
4357        return;
4358
4359
4360  // Special case: check for comparisons against literals that can be exactly
4361  //  represented by APFloat.  In such cases, do not emit a warning.  This
4362  //  is a heuristic: often comparison against such literals are used to
4363  //  detect if a value in a variable has not changed.  This clearly can
4364  //  lead to false negatives.
4365  if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4366    if (FLL->isExact())
4367      return;
4368  } else
4369    if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4370      if (FLR->isExact())
4371        return;
4372
4373  // Check for comparisons with builtin types.
4374  if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4375    if (CL->isBuiltinCall())
4376      return;
4377
4378  if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4379    if (CR->isBuiltinCall())
4380      return;
4381
4382  // Emit the diagnostic.
4383  Diag(Loc, diag::warn_floatingpoint_eq)
4384    << LHS->getSourceRange() << RHS->getSourceRange();
4385}
4386
4387//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4388//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
4389
4390namespace {
4391
4392/// Structure recording the 'active' range of an integer-valued
4393/// expression.
4394struct IntRange {
4395  /// The number of bits active in the int.
4396  unsigned Width;
4397
4398  /// True if the int is known not to have negative values.
4399  bool NonNegative;
4400
4401  IntRange(unsigned Width, bool NonNegative)
4402    : Width(Width), NonNegative(NonNegative)
4403  {}
4404
4405  /// Returns the range of the bool type.
4406  static IntRange forBoolType() {
4407    return IntRange(1, true);
4408  }
4409
4410  /// Returns the range of an opaque value of the given integral type.
4411  static IntRange forValueOfType(ASTContext &C, QualType T) {
4412    return forValueOfCanonicalType(C,
4413                          T->getCanonicalTypeInternal().getTypePtr());
4414  }
4415
4416  /// Returns the range of an opaque value of a canonical integral type.
4417  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
4418    assert(T->isCanonicalUnqualified());
4419
4420    if (const VectorType *VT = dyn_cast<VectorType>(T))
4421      T = VT->getElementType().getTypePtr();
4422    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4423      T = CT->getElementType().getTypePtr();
4424
4425    // For enum types, use the known bit width of the enumerators.
4426    if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4427      EnumDecl *Enum = ET->getDecl();
4428      if (!Enum->isCompleteDefinition())
4429        return IntRange(C.getIntWidth(QualType(T, 0)), false);
4430
4431      unsigned NumPositive = Enum->getNumPositiveBits();
4432      unsigned NumNegative = Enum->getNumNegativeBits();
4433
4434      if (NumNegative == 0)
4435        return IntRange(NumPositive, true/*NonNegative*/);
4436      else
4437        return IntRange(std::max(NumPositive + 1, NumNegative),
4438                        false/*NonNegative*/);
4439    }
4440
4441    const BuiltinType *BT = cast<BuiltinType>(T);
4442    assert(BT->isInteger());
4443
4444    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4445  }
4446
4447  /// Returns the "target" range of a canonical integral type, i.e.
4448  /// the range of values expressible in the type.
4449  ///
4450  /// This matches forValueOfCanonicalType except that enums have the
4451  /// full range of their type, not the range of their enumerators.
4452  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4453    assert(T->isCanonicalUnqualified());
4454
4455    if (const VectorType *VT = dyn_cast<VectorType>(T))
4456      T = VT->getElementType().getTypePtr();
4457    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4458      T = CT->getElementType().getTypePtr();
4459    if (const EnumType *ET = dyn_cast<EnumType>(T))
4460      T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
4461
4462    const BuiltinType *BT = cast<BuiltinType>(T);
4463    assert(BT->isInteger());
4464
4465    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4466  }
4467
4468  /// Returns the supremum of two ranges: i.e. their conservative merge.
4469  static IntRange join(IntRange L, IntRange R) {
4470    return IntRange(std::max(L.Width, R.Width),
4471                    L.NonNegative && R.NonNegative);
4472  }
4473
4474  /// Returns the infinum of two ranges: i.e. their aggressive merge.
4475  static IntRange meet(IntRange L, IntRange R) {
4476    return IntRange(std::min(L.Width, R.Width),
4477                    L.NonNegative || R.NonNegative);
4478  }
4479};
4480
4481static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4482                              unsigned MaxWidth) {
4483  if (value.isSigned() && value.isNegative())
4484    return IntRange(value.getMinSignedBits(), false);
4485
4486  if (value.getBitWidth() > MaxWidth)
4487    value = value.trunc(MaxWidth);
4488
4489  // isNonNegative() just checks the sign bit without considering
4490  // signedness.
4491  return IntRange(value.getActiveBits(), true);
4492}
4493
4494static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4495                              unsigned MaxWidth) {
4496  if (result.isInt())
4497    return GetValueRange(C, result.getInt(), MaxWidth);
4498
4499  if (result.isVector()) {
4500    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4501    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4502      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4503      R = IntRange::join(R, El);
4504    }
4505    return R;
4506  }
4507
4508  if (result.isComplexInt()) {
4509    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4510    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4511    return IntRange::join(R, I);
4512  }
4513
4514  // This can happen with lossless casts to intptr_t of "based" lvalues.
4515  // Assume it might use arbitrary bits.
4516  // FIXME: The only reason we need to pass the type in here is to get
4517  // the sign right on this one case.  It would be nice if APValue
4518  // preserved this.
4519  assert(result.isLValue() || result.isAddrLabelDiff());
4520  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4521}
4522
4523static QualType GetExprType(Expr *E) {
4524  QualType Ty = E->getType();
4525  if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4526    Ty = AtomicRHS->getValueType();
4527  return Ty;
4528}
4529
4530/// Pseudo-evaluate the given integer expression, estimating the
4531/// range of values it might take.
4532///
4533/// \param MaxWidth - the width to which the value will be truncated
4534static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4535  E = E->IgnoreParens();
4536
4537  // Try a full evaluation first.
4538  Expr::EvalResult result;
4539  if (E->EvaluateAsRValue(result, C))
4540    return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
4541
4542  // I think we only want to look through implicit casts here; if the
4543  // user has an explicit widening cast, we should treat the value as
4544  // being of the new, wider type.
4545  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4546    if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
4547      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4548
4549    IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
4550
4551    bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
4552
4553    // Assume that non-integer casts can span the full range of the type.
4554    if (!isIntegerCast)
4555      return OutputTypeRange;
4556
4557    IntRange SubRange
4558      = GetExprRange(C, CE->getSubExpr(),
4559                     std::min(MaxWidth, OutputTypeRange.Width));
4560
4561    // Bail out if the subexpr's range is as wide as the cast type.
4562    if (SubRange.Width >= OutputTypeRange.Width)
4563      return OutputTypeRange;
4564
4565    // Otherwise, we take the smaller width, and we're non-negative if
4566    // either the output type or the subexpr is.
4567    return IntRange(SubRange.Width,
4568                    SubRange.NonNegative || OutputTypeRange.NonNegative);
4569  }
4570
4571  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4572    // If we can fold the condition, just take that operand.
4573    bool CondResult;
4574    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4575      return GetExprRange(C, CondResult ? CO->getTrueExpr()
4576                                        : CO->getFalseExpr(),
4577                          MaxWidth);
4578
4579    // Otherwise, conservatively merge.
4580    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4581    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4582    return IntRange::join(L, R);
4583  }
4584
4585  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4586    switch (BO->getOpcode()) {
4587
4588    // Boolean-valued operations are single-bit and positive.
4589    case BO_LAnd:
4590    case BO_LOr:
4591    case BO_LT:
4592    case BO_GT:
4593    case BO_LE:
4594    case BO_GE:
4595    case BO_EQ:
4596    case BO_NE:
4597      return IntRange::forBoolType();
4598
4599    // The type of the assignments is the type of the LHS, so the RHS
4600    // is not necessarily the same type.
4601    case BO_MulAssign:
4602    case BO_DivAssign:
4603    case BO_RemAssign:
4604    case BO_AddAssign:
4605    case BO_SubAssign:
4606    case BO_XorAssign:
4607    case BO_OrAssign:
4608      // TODO: bitfields?
4609      return IntRange::forValueOfType(C, GetExprType(E));
4610
4611    // Simple assignments just pass through the RHS, which will have
4612    // been coerced to the LHS type.
4613    case BO_Assign:
4614      // TODO: bitfields?
4615      return GetExprRange(C, BO->getRHS(), MaxWidth);
4616
4617    // Operations with opaque sources are black-listed.
4618    case BO_PtrMemD:
4619    case BO_PtrMemI:
4620      return IntRange::forValueOfType(C, GetExprType(E));
4621
4622    // Bitwise-and uses the *infinum* of the two source ranges.
4623    case BO_And:
4624    case BO_AndAssign:
4625      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4626                            GetExprRange(C, BO->getRHS(), MaxWidth));
4627
4628    // Left shift gets black-listed based on a judgement call.
4629    case BO_Shl:
4630      // ...except that we want to treat '1 << (blah)' as logically
4631      // positive.  It's an important idiom.
4632      if (IntegerLiteral *I
4633            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4634        if (I->getValue() == 1) {
4635          IntRange R = IntRange::forValueOfType(C, GetExprType(E));
4636          return IntRange(R.Width, /*NonNegative*/ true);
4637        }
4638      }
4639      // fallthrough
4640
4641    case BO_ShlAssign:
4642      return IntRange::forValueOfType(C, GetExprType(E));
4643
4644    // Right shift by a constant can narrow its left argument.
4645    case BO_Shr:
4646    case BO_ShrAssign: {
4647      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4648
4649      // If the shift amount is a positive constant, drop the width by
4650      // that much.
4651      llvm::APSInt shift;
4652      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4653          shift.isNonNegative()) {
4654        unsigned zext = shift.getZExtValue();
4655        if (zext >= L.Width)
4656          L.Width = (L.NonNegative ? 0 : 1);
4657        else
4658          L.Width -= zext;
4659      }
4660
4661      return L;
4662    }
4663
4664    // Comma acts as its right operand.
4665    case BO_Comma:
4666      return GetExprRange(C, BO->getRHS(), MaxWidth);
4667
4668    // Black-list pointer subtractions.
4669    case BO_Sub:
4670      if (BO->getLHS()->getType()->isPointerType())
4671        return IntRange::forValueOfType(C, GetExprType(E));
4672      break;
4673
4674    // The width of a division result is mostly determined by the size
4675    // of the LHS.
4676    case BO_Div: {
4677      // Don't 'pre-truncate' the operands.
4678      unsigned opWidth = C.getIntWidth(GetExprType(E));
4679      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4680
4681      // If the divisor is constant, use that.
4682      llvm::APSInt divisor;
4683      if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4684        unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4685        if (log2 >= L.Width)
4686          L.Width = (L.NonNegative ? 0 : 1);
4687        else
4688          L.Width = std::min(L.Width - log2, MaxWidth);
4689        return L;
4690      }
4691
4692      // Otherwise, just use the LHS's width.
4693      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4694      return IntRange(L.Width, L.NonNegative && R.NonNegative);
4695    }
4696
4697    // The result of a remainder can't be larger than the result of
4698    // either side.
4699    case BO_Rem: {
4700      // Don't 'pre-truncate' the operands.
4701      unsigned opWidth = C.getIntWidth(GetExprType(E));
4702      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4703      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4704
4705      IntRange meet = IntRange::meet(L, R);
4706      meet.Width = std::min(meet.Width, MaxWidth);
4707      return meet;
4708    }
4709
4710    // The default behavior is okay for these.
4711    case BO_Mul:
4712    case BO_Add:
4713    case BO_Xor:
4714    case BO_Or:
4715      break;
4716    }
4717
4718    // The default case is to treat the operation as if it were closed
4719    // on the narrowest type that encompasses both operands.
4720    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4721    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4722    return IntRange::join(L, R);
4723  }
4724
4725  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4726    switch (UO->getOpcode()) {
4727    // Boolean-valued operations are white-listed.
4728    case UO_LNot:
4729      return IntRange::forBoolType();
4730
4731    // Operations with opaque sources are black-listed.
4732    case UO_Deref:
4733    case UO_AddrOf: // should be impossible
4734      return IntRange::forValueOfType(C, GetExprType(E));
4735
4736    default:
4737      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4738    }
4739  }
4740
4741  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4742    return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4743
4744  if (FieldDecl *BitField = E->getSourceBitField())
4745    return IntRange(BitField->getBitWidthValue(C),
4746                    BitField->getType()->isUnsignedIntegerOrEnumerationType());
4747
4748  return IntRange::forValueOfType(C, GetExprType(E));
4749}
4750
4751static IntRange GetExprRange(ASTContext &C, Expr *E) {
4752  return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
4753}
4754
4755/// Checks whether the given value, which currently has the given
4756/// source semantics, has the same value when coerced through the
4757/// target semantics.
4758static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4759                                 const llvm::fltSemantics &Src,
4760                                 const llvm::fltSemantics &Tgt) {
4761  llvm::APFloat truncated = value;
4762
4763  bool ignored;
4764  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4765  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4766
4767  return truncated.bitwiseIsEqual(value);
4768}
4769
4770/// Checks whether the given value, which currently has the given
4771/// source semantics, has the same value when coerced through the
4772/// target semantics.
4773///
4774/// The value might be a vector of floats (or a complex number).
4775static bool IsSameFloatAfterCast(const APValue &value,
4776                                 const llvm::fltSemantics &Src,
4777                                 const llvm::fltSemantics &Tgt) {
4778  if (value.isFloat())
4779    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4780
4781  if (value.isVector()) {
4782    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4783      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4784        return false;
4785    return true;
4786  }
4787
4788  assert(value.isComplexFloat());
4789  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4790          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4791}
4792
4793static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
4794
4795static bool IsZero(Sema &S, Expr *E) {
4796  // Suppress cases where we are comparing against an enum constant.
4797  if (const DeclRefExpr *DR =
4798      dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4799    if (isa<EnumConstantDecl>(DR->getDecl()))
4800      return false;
4801
4802  // Suppress cases where the '0' value is expanded from a macro.
4803  if (E->getLocStart().isMacroID())
4804    return false;
4805
4806  llvm::APSInt Value;
4807  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4808}
4809
4810static bool HasEnumType(Expr *E) {
4811  // Strip off implicit integral promotions.
4812  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4813    if (ICE->getCastKind() != CK_IntegralCast &&
4814        ICE->getCastKind() != CK_NoOp)
4815      break;
4816    E = ICE->getSubExpr();
4817  }
4818
4819  return E->getType()->isEnumeralType();
4820}
4821
4822static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
4823  // Disable warning in template instantiations.
4824  if (!S.ActiveTemplateInstantiations.empty())
4825    return;
4826
4827  BinaryOperatorKind op = E->getOpcode();
4828  if (E->isValueDependent())
4829    return;
4830
4831  if (op == BO_LT && IsZero(S, E->getRHS())) {
4832    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4833      << "< 0" << "false" << HasEnumType(E->getLHS())
4834      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4835  } else if (op == BO_GE && IsZero(S, E->getRHS())) {
4836    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4837      << ">= 0" << "true" << HasEnumType(E->getLHS())
4838      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4839  } else if (op == BO_GT && IsZero(S, E->getLHS())) {
4840    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4841      << "0 >" << "false" << HasEnumType(E->getRHS())
4842      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4843  } else if (op == BO_LE && IsZero(S, E->getLHS())) {
4844    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4845      << "0 <=" << "true" << HasEnumType(E->getRHS())
4846      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4847  }
4848}
4849
4850static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
4851                                         Expr *Constant, Expr *Other,
4852                                         llvm::APSInt Value,
4853                                         bool RhsConstant) {
4854  // Disable warning in template instantiations.
4855  if (!S.ActiveTemplateInstantiations.empty())
4856    return;
4857
4858  // 0 values are handled later by CheckTrivialUnsignedComparison().
4859  if (Value == 0)
4860    return;
4861
4862  BinaryOperatorKind op = E->getOpcode();
4863  QualType OtherT = Other->getType();
4864  QualType ConstantT = Constant->getType();
4865  QualType CommonT = E->getLHS()->getType();
4866  if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
4867    return;
4868  assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
4869         && "comparison with non-integer type");
4870
4871  bool ConstantSigned = ConstantT->isSignedIntegerType();
4872  bool CommonSigned = CommonT->isSignedIntegerType();
4873
4874  bool EqualityOnly = false;
4875
4876  // TODO: Investigate using GetExprRange() to get tighter bounds on
4877  // on the bit ranges.
4878  IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
4879  unsigned OtherWidth = OtherRange.Width;
4880
4881  if (CommonSigned) {
4882    // The common type is signed, therefore no signed to unsigned conversion.
4883    if (!OtherRange.NonNegative) {
4884      // Check that the constant is representable in type OtherT.
4885      if (ConstantSigned) {
4886        if (OtherWidth >= Value.getMinSignedBits())
4887          return;
4888      } else { // !ConstantSigned
4889        if (OtherWidth >= Value.getActiveBits() + 1)
4890          return;
4891      }
4892    } else { // !OtherSigned
4893      // Check that the constant is representable in type OtherT.
4894      // Negative values are out of range.
4895      if (ConstantSigned) {
4896        if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4897          return;
4898      } else { // !ConstantSigned
4899        if (OtherWidth >= Value.getActiveBits())
4900          return;
4901      }
4902    }
4903  } else {  // !CommonSigned
4904    if (OtherRange.NonNegative) {
4905      if (OtherWidth >= Value.getActiveBits())
4906        return;
4907    } else if (!OtherRange.NonNegative && !ConstantSigned) {
4908      // Check to see if the constant is representable in OtherT.
4909      if (OtherWidth > Value.getActiveBits())
4910        return;
4911      // Check to see if the constant is equivalent to a negative value
4912      // cast to CommonT.
4913      if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
4914          Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
4915        return;
4916      // The constant value rests between values that OtherT can represent after
4917      // conversion.  Relational comparison still works, but equality
4918      // comparisons will be tautological.
4919      EqualityOnly = true;
4920    } else { // OtherSigned && ConstantSigned
4921      assert(0 && "Two signed types converted to unsigned types.");
4922    }
4923  }
4924
4925  bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4926
4927  bool IsTrue = true;
4928  if (op == BO_EQ || op == BO_NE) {
4929    IsTrue = op == BO_NE;
4930  } else if (EqualityOnly) {
4931    return;
4932  } else if (RhsConstant) {
4933    if (op == BO_GT || op == BO_GE)
4934      IsTrue = !PositiveConstant;
4935    else // op == BO_LT || op == BO_LE
4936      IsTrue = PositiveConstant;
4937  } else {
4938    if (op == BO_LT || op == BO_LE)
4939      IsTrue = !PositiveConstant;
4940    else // op == BO_GT || op == BO_GE
4941      IsTrue = PositiveConstant;
4942  }
4943
4944  // If this is a comparison to an enum constant, include that
4945  // constant in the diagnostic.
4946  const EnumConstantDecl *ED = 0;
4947  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4948    ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4949
4950  SmallString<64> PrettySourceValue;
4951  llvm::raw_svector_ostream OS(PrettySourceValue);
4952  if (ED)
4953    OS << '\'' << *ED << "' (" << Value << ")";
4954  else
4955    OS << Value;
4956
4957  S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
4958      << OS.str() << OtherT << IsTrue
4959      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4960}
4961
4962/// Analyze the operands of the given comparison.  Implements the
4963/// fallback case from AnalyzeComparison.
4964static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
4965  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4966  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4967}
4968
4969/// \brief Implements -Wsign-compare.
4970///
4971/// \param E the binary operator to check for warnings
4972static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
4973  // The type the comparison is being performed in.
4974  QualType T = E->getLHS()->getType();
4975  assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4976         && "comparison with mismatched types");
4977  if (E->isValueDependent())
4978    return AnalyzeImpConvsInComparison(S, E);
4979
4980  Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4981  Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
4982
4983  bool IsComparisonConstant = false;
4984
4985  // Check whether an integer constant comparison results in a value
4986  // of 'true' or 'false'.
4987  if (T->isIntegralType(S.Context)) {
4988    llvm::APSInt RHSValue;
4989    bool IsRHSIntegralLiteral =
4990      RHS->isIntegerConstantExpr(RHSValue, S.Context);
4991    llvm::APSInt LHSValue;
4992    bool IsLHSIntegralLiteral =
4993      LHS->isIntegerConstantExpr(LHSValue, S.Context);
4994    if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4995        DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4996    else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4997      DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4998    else
4999      IsComparisonConstant =
5000        (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
5001  } else if (!T->hasUnsignedIntegerRepresentation())
5002      IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
5003
5004  // We don't do anything special if this isn't an unsigned integral
5005  // comparison:  we're only interested in integral comparisons, and
5006  // signed comparisons only happen in cases we don't care to warn about.
5007  //
5008  // We also don't care about value-dependent expressions or expressions
5009  // whose result is a constant.
5010  if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
5011    return AnalyzeImpConvsInComparison(S, E);
5012
5013  // Check to see if one of the (unmodified) operands is of different
5014  // signedness.
5015  Expr *signedOperand, *unsignedOperand;
5016  if (LHS->getType()->hasSignedIntegerRepresentation()) {
5017    assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
5018           "unsigned comparison between two signed integer expressions?");
5019    signedOperand = LHS;
5020    unsignedOperand = RHS;
5021  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5022    signedOperand = RHS;
5023    unsignedOperand = LHS;
5024  } else {
5025    CheckTrivialUnsignedComparison(S, E);
5026    return AnalyzeImpConvsInComparison(S, E);
5027  }
5028
5029  // Otherwise, calculate the effective range of the signed operand.
5030  IntRange signedRange = GetExprRange(S.Context, signedOperand);
5031
5032  // Go ahead and analyze implicit conversions in the operands.  Note
5033  // that we skip the implicit conversions on both sides.
5034  AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5035  AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
5036
5037  // If the signed range is non-negative, -Wsign-compare won't fire,
5038  // but we should still check for comparisons which are always true
5039  // or false.
5040  if (signedRange.NonNegative)
5041    return CheckTrivialUnsignedComparison(S, E);
5042
5043  // For (in)equality comparisons, if the unsigned operand is a
5044  // constant which cannot collide with a overflowed signed operand,
5045  // then reinterpreting the signed operand as unsigned will not
5046  // change the result of the comparison.
5047  if (E->isEqualityOp()) {
5048    unsigned comparisonWidth = S.Context.getIntWidth(T);
5049    IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
5050
5051    // We should never be unable to prove that the unsigned operand is
5052    // non-negative.
5053    assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5054
5055    if (unsignedRange.Width < comparisonWidth)
5056      return;
5057  }
5058
5059  S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5060    S.PDiag(diag::warn_mixed_sign_comparison)
5061      << LHS->getType() << RHS->getType()
5062      << LHS->getSourceRange() << RHS->getSourceRange());
5063}
5064
5065/// Analyzes an attempt to assign the given value to a bitfield.
5066///
5067/// Returns true if there was something fishy about the attempt.
5068static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5069                                      SourceLocation InitLoc) {
5070  assert(Bitfield->isBitField());
5071  if (Bitfield->isInvalidDecl())
5072    return false;
5073
5074  // White-list bool bitfields.
5075  if (Bitfield->getType()->isBooleanType())
5076    return false;
5077
5078  // Ignore value- or type-dependent expressions.
5079  if (Bitfield->getBitWidth()->isValueDependent() ||
5080      Bitfield->getBitWidth()->isTypeDependent() ||
5081      Init->isValueDependent() ||
5082      Init->isTypeDependent())
5083    return false;
5084
5085  Expr *OriginalInit = Init->IgnoreParenImpCasts();
5086
5087  llvm::APSInt Value;
5088  if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
5089    return false;
5090
5091  unsigned OriginalWidth = Value.getBitWidth();
5092  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
5093
5094  if (OriginalWidth <= FieldWidth)
5095    return false;
5096
5097  // Compute the value which the bitfield will contain.
5098  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
5099  TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
5100
5101  // Check whether the stored value is equal to the original value.
5102  TruncatedValue = TruncatedValue.extend(OriginalWidth);
5103  if (llvm::APSInt::isSameValue(Value, TruncatedValue))
5104    return false;
5105
5106  // Special-case bitfields of width 1: booleans are naturally 0/1, and
5107  // therefore don't strictly fit into a signed bitfield of width 1.
5108  if (FieldWidth == 1 && Value == 1)
5109    return false;
5110
5111  std::string PrettyValue = Value.toString(10);
5112  std::string PrettyTrunc = TruncatedValue.toString(10);
5113
5114  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5115    << PrettyValue << PrettyTrunc << OriginalInit->getType()
5116    << Init->getSourceRange();
5117
5118  return true;
5119}
5120
5121/// Analyze the given simple or compound assignment for warning-worthy
5122/// operations.
5123static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
5124  // Just recurse on the LHS.
5125  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5126
5127  // We want to recurse on the RHS as normal unless we're assigning to
5128  // a bitfield.
5129  if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
5130    if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
5131                                  E->getOperatorLoc())) {
5132      // Recurse, ignoring any implicit conversions on the RHS.
5133      return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5134                                        E->getOperatorLoc());
5135    }
5136  }
5137
5138  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5139}
5140
5141/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5142static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
5143                            SourceLocation CContext, unsigned diag,
5144                            bool pruneControlFlow = false) {
5145  if (pruneControlFlow) {
5146    S.DiagRuntimeBehavior(E->getExprLoc(), E,
5147                          S.PDiag(diag)
5148                            << SourceType << T << E->getSourceRange()
5149                            << SourceRange(CContext));
5150    return;
5151  }
5152  S.Diag(E->getExprLoc(), diag)
5153    << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5154}
5155
5156/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5157static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
5158                            SourceLocation CContext, unsigned diag,
5159                            bool pruneControlFlow = false) {
5160  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
5161}
5162
5163/// Diagnose an implicit cast from a literal expression. Does not warn when the
5164/// cast wouldn't lose information.
5165void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5166                                    SourceLocation CContext) {
5167  // Try to convert the literal exactly to an integer. If we can, don't warn.
5168  bool isExact = false;
5169  const llvm::APFloat &Value = FL->getValue();
5170  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5171                            T->hasUnsignedIntegerRepresentation());
5172  if (Value.convertToInteger(IntegerValue,
5173                             llvm::APFloat::rmTowardZero, &isExact)
5174      == llvm::APFloat::opOK && isExact)
5175    return;
5176
5177  // FIXME: Force the precision of the source value down so we don't print
5178  // digits which are usually useless (we don't really care here if we
5179  // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
5180  // would automatically print the shortest representation, but it's a bit
5181  // tricky to implement.
5182  SmallString<16> PrettySourceValue;
5183  unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5184  precision = (precision * 59 + 195) / 196;
5185  Value.toString(PrettySourceValue, precision);
5186
5187  SmallString<16> PrettyTargetValue;
5188  if (T->isSpecificBuiltinType(BuiltinType::Bool))
5189    PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5190  else
5191    IntegerValue.toString(PrettyTargetValue);
5192
5193  S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
5194    << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5195    << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
5196}
5197
5198std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5199  if (!Range.Width) return "0";
5200
5201  llvm::APSInt ValueInRange = Value;
5202  ValueInRange.setIsSigned(!Range.NonNegative);
5203  ValueInRange = ValueInRange.trunc(Range.Width);
5204  return ValueInRange.toString(10);
5205}
5206
5207static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5208  if (!isa<ImplicitCastExpr>(Ex))
5209    return false;
5210
5211  Expr *InnerE = Ex->IgnoreParenImpCasts();
5212  const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5213  const Type *Source =
5214    S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5215  if (Target->isDependentType())
5216    return false;
5217
5218  const BuiltinType *FloatCandidateBT =
5219    dyn_cast<BuiltinType>(ToBool ? Source : Target);
5220  const Type *BoolCandidateType = ToBool ? Target : Source;
5221
5222  return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5223          FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5224}
5225
5226void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5227                                      SourceLocation CC) {
5228  unsigned NumArgs = TheCall->getNumArgs();
5229  for (unsigned i = 0; i < NumArgs; ++i) {
5230    Expr *CurrA = TheCall->getArg(i);
5231    if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5232      continue;
5233
5234    bool IsSwapped = ((i > 0) &&
5235        IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5236    IsSwapped |= ((i < (NumArgs - 1)) &&
5237        IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5238    if (IsSwapped) {
5239      // Warn on this floating-point to bool conversion.
5240      DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5241                      CurrA->getType(), CC,
5242                      diag::warn_impcast_floating_point_to_bool);
5243    }
5244  }
5245}
5246
5247void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
5248                             SourceLocation CC, bool *ICContext = 0) {
5249  if (E->isTypeDependent() || E->isValueDependent()) return;
5250
5251  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5252  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5253  if (Source == Target) return;
5254  if (Target->isDependentType()) return;
5255
5256  // If the conversion context location is invalid don't complain. We also
5257  // don't want to emit a warning if the issue occurs from the expansion of
5258  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5259  // delay this check as long as possible. Once we detect we are in that
5260  // scenario, we just return.
5261  if (CC.isInvalid())
5262    return;
5263
5264  // Diagnose implicit casts to bool.
5265  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5266    if (isa<StringLiteral>(E))
5267      // Warn on string literal to bool.  Checks for string literals in logical
5268      // expressions, for instances, assert(0 && "error here"), is prevented
5269      // by a check in AnalyzeImplicitConversions().
5270      return DiagnoseImpCast(S, E, T, CC,
5271                             diag::warn_impcast_string_literal_to_bool);
5272    if (Source->isFunctionType()) {
5273      // Warn on function to bool. Checks free functions and static member
5274      // functions. Weakly imported functions are excluded from the check,
5275      // since it's common to test their value to check whether the linker
5276      // found a definition for them.
5277      ValueDecl *D = 0;
5278      if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5279        D = R->getDecl();
5280      } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5281        D = M->getMemberDecl();
5282      }
5283
5284      if (D && !D->isWeak()) {
5285        if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5286          S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5287            << F << E->getSourceRange() << SourceRange(CC);
5288          S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5289            << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5290          QualType ReturnType;
5291          UnresolvedSet<4> NonTemplateOverloads;
5292          S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
5293          if (!ReturnType.isNull()
5294              && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5295            S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5296              << FixItHint::CreateInsertion(
5297                 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
5298          return;
5299        }
5300      }
5301    }
5302  }
5303
5304  // Strip vector types.
5305  if (isa<VectorType>(Source)) {
5306    if (!isa<VectorType>(Target)) {
5307      if (S.SourceMgr.isInSystemMacro(CC))
5308        return;
5309      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
5310    }
5311
5312    // If the vector cast is cast between two vectors of the same size, it is
5313    // a bitcast, not a conversion.
5314    if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5315      return;
5316
5317    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5318    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5319  }
5320
5321  // Strip complex types.
5322  if (isa<ComplexType>(Source)) {
5323    if (!isa<ComplexType>(Target)) {
5324      if (S.SourceMgr.isInSystemMacro(CC))
5325        return;
5326
5327      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
5328    }
5329
5330    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5331    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5332  }
5333
5334  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5335  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5336
5337  // If the source is floating point...
5338  if (SourceBT && SourceBT->isFloatingPoint()) {
5339    // ...and the target is floating point...
5340    if (TargetBT && TargetBT->isFloatingPoint()) {
5341      // ...then warn if we're dropping FP rank.
5342
5343      // Builtin FP kinds are ordered by increasing FP rank.
5344      if (SourceBT->getKind() > TargetBT->getKind()) {
5345        // Don't warn about float constants that are precisely
5346        // representable in the target type.
5347        Expr::EvalResult result;
5348        if (E->EvaluateAsRValue(result, S.Context)) {
5349          // Value might be a float, a float vector, or a float complex.
5350          if (IsSameFloatAfterCast(result.Val,
5351                   S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5352                   S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
5353            return;
5354        }
5355
5356        if (S.SourceMgr.isInSystemMacro(CC))
5357          return;
5358
5359        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
5360      }
5361      return;
5362    }
5363
5364    // If the target is integral, always warn.
5365    if (TargetBT && TargetBT->isInteger()) {
5366      if (S.SourceMgr.isInSystemMacro(CC))
5367        return;
5368
5369      Expr *InnerE = E->IgnoreParenImpCasts();
5370      // We also want to warn on, e.g., "int i = -1.234"
5371      if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5372        if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5373          InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5374
5375      if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5376        DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
5377      } else {
5378        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5379      }
5380    }
5381
5382    // If the target is bool, warn if expr is a function or method call.
5383    if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5384        isa<CallExpr>(E)) {
5385      // Check last argument of function call to see if it is an
5386      // implicit cast from a type matching the type the result
5387      // is being cast to.
5388      CallExpr *CEx = cast<CallExpr>(E);
5389      unsigned NumArgs = CEx->getNumArgs();
5390      if (NumArgs > 0) {
5391        Expr *LastA = CEx->getArg(NumArgs - 1);
5392        Expr *InnerE = LastA->IgnoreParenImpCasts();
5393        const Type *InnerType =
5394          S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5395        if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5396          // Warn on this floating-point to bool conversion
5397          DiagnoseImpCast(S, E, T, CC,
5398                          diag::warn_impcast_floating_point_to_bool);
5399        }
5400      }
5401    }
5402    return;
5403  }
5404
5405  if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
5406           == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
5407      && !Target->isBlockPointerType() && !Target->isMemberPointerType()
5408      && Target->isScalarType() && !Target->isNullPtrType()) {
5409    SourceLocation Loc = E->getSourceRange().getBegin();
5410    if (Loc.isMacroID())
5411      Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
5412    if (!Loc.isMacroID() || CC.isMacroID())
5413      S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5414          << T << clang::SourceRange(CC)
5415          << FixItHint::CreateReplacement(Loc,
5416                                          S.getFixItZeroLiteralForType(T, Loc));
5417  }
5418
5419  if (!Source->isIntegerType() || !Target->isIntegerType())
5420    return;
5421
5422  // TODO: remove this early return once the false positives for constant->bool
5423  // in templates, macros, etc, are reduced or removed.
5424  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5425    return;
5426
5427  IntRange SourceRange = GetExprRange(S.Context, E);
5428  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
5429
5430  if (SourceRange.Width > TargetRange.Width) {
5431    // If the source is a constant, use a default-on diagnostic.
5432    // TODO: this should happen for bitfield stores, too.
5433    llvm::APSInt Value(32);
5434    if (E->isIntegerConstantExpr(Value, S.Context)) {
5435      if (S.SourceMgr.isInSystemMacro(CC))
5436        return;
5437
5438      std::string PrettySourceValue = Value.toString(10);
5439      std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
5440
5441      S.DiagRuntimeBehavior(E->getExprLoc(), E,
5442        S.PDiag(diag::warn_impcast_integer_precision_constant)
5443            << PrettySourceValue << PrettyTargetValue
5444            << E->getType() << T << E->getSourceRange()
5445            << clang::SourceRange(CC));
5446      return;
5447    }
5448
5449    // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5450    if (S.SourceMgr.isInSystemMacro(CC))
5451      return;
5452
5453    if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
5454      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5455                             /* pruneControlFlow */ true);
5456    return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
5457  }
5458
5459  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5460      (!TargetRange.NonNegative && SourceRange.NonNegative &&
5461       SourceRange.Width == TargetRange.Width)) {
5462
5463    if (S.SourceMgr.isInSystemMacro(CC))
5464      return;
5465
5466    unsigned DiagID = diag::warn_impcast_integer_sign;
5467
5468    // Traditionally, gcc has warned about this under -Wsign-compare.
5469    // We also want to warn about it in -Wconversion.
5470    // So if -Wconversion is off, use a completely identical diagnostic
5471    // in the sign-compare group.
5472    // The conditional-checking code will
5473    if (ICContext) {
5474      DiagID = diag::warn_impcast_integer_sign_conditional;
5475      *ICContext = true;
5476    }
5477
5478    return DiagnoseImpCast(S, E, T, CC, DiagID);
5479  }
5480
5481  // Diagnose conversions between different enumeration types.
5482  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5483  // type, to give us better diagnostics.
5484  QualType SourceType = E->getType();
5485  if (!S.getLangOpts().CPlusPlus) {
5486    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5487      if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5488        EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5489        SourceType = S.Context.getTypeDeclType(Enum);
5490        Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5491      }
5492  }
5493
5494  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5495    if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5496      if (SourceEnum->getDecl()->hasNameForLinkage() &&
5497          TargetEnum->getDecl()->hasNameForLinkage() &&
5498          SourceEnum != TargetEnum) {
5499        if (S.SourceMgr.isInSystemMacro(CC))
5500          return;
5501
5502        return DiagnoseImpCast(S, E, SourceType, T, CC,
5503                               diag::warn_impcast_different_enum_types);
5504      }
5505
5506  return;
5507}
5508
5509void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5510                              SourceLocation CC, QualType T);
5511
5512void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
5513                             SourceLocation CC, bool &ICContext) {
5514  E = E->IgnoreParenImpCasts();
5515
5516  if (isa<ConditionalOperator>(E))
5517    return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
5518
5519  AnalyzeImplicitConversions(S, E, CC);
5520  if (E->getType() != T)
5521    return CheckImplicitConversion(S, E, T, CC, &ICContext);
5522  return;
5523}
5524
5525void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5526                              SourceLocation CC, QualType T) {
5527  AnalyzeImplicitConversions(S, E->getCond(), CC);
5528
5529  bool Suspicious = false;
5530  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5531  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
5532
5533  // If -Wconversion would have warned about either of the candidates
5534  // for a signedness conversion to the context type...
5535  if (!Suspicious) return;
5536
5537  // ...but it's currently ignored...
5538  if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5539                                 CC))
5540    return;
5541
5542  // ...then check whether it would have warned about either of the
5543  // candidates for a signedness conversion to the condition type.
5544  if (E->getType() == T) return;
5545
5546  Suspicious = false;
5547  CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5548                          E->getType(), CC, &Suspicious);
5549  if (!Suspicious)
5550    CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
5551                            E->getType(), CC, &Suspicious);
5552}
5553
5554/// AnalyzeImplicitConversions - Find and report any interesting
5555/// implicit conversions in the given expression.  There are a couple
5556/// of competing diagnostics here, -Wconversion and -Wsign-compare.
5557void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
5558  QualType T = OrigE->getType();
5559  Expr *E = OrigE->IgnoreParenImpCasts();
5560
5561  if (E->isTypeDependent() || E->isValueDependent())
5562    return;
5563
5564  // For conditional operators, we analyze the arguments as if they
5565  // were being fed directly into the output.
5566  if (isa<ConditionalOperator>(E)) {
5567    ConditionalOperator *CO = cast<ConditionalOperator>(E);
5568    CheckConditionalOperator(S, CO, CC, T);
5569    return;
5570  }
5571
5572  // Check implicit argument conversions for function calls.
5573  if (CallExpr *Call = dyn_cast<CallExpr>(E))
5574    CheckImplicitArgumentConversions(S, Call, CC);
5575
5576  // Go ahead and check any implicit conversions we might have skipped.
5577  // The non-canonical typecheck is just an optimization;
5578  // CheckImplicitConversion will filter out dead implicit conversions.
5579  if (E->getType() != T)
5580    CheckImplicitConversion(S, E, T, CC);
5581
5582  // Now continue drilling into this expression.
5583
5584  if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
5585    if (POE->getResultExpr())
5586      E = POE->getResultExpr();
5587  }
5588
5589  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5590    return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5591
5592  // Skip past explicit casts.
5593  if (isa<ExplicitCastExpr>(E)) {
5594    E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
5595    return AnalyzeImplicitConversions(S, E, CC);
5596  }
5597
5598  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5599    // Do a somewhat different check with comparison operators.
5600    if (BO->isComparisonOp())
5601      return AnalyzeComparison(S, BO);
5602
5603    // And with simple assignments.
5604    if (BO->getOpcode() == BO_Assign)
5605      return AnalyzeAssignment(S, BO);
5606  }
5607
5608  // These break the otherwise-useful invariant below.  Fortunately,
5609  // we don't really need to recurse into them, because any internal
5610  // expressions should have been analyzed already when they were
5611  // built into statements.
5612  if (isa<StmtExpr>(E)) return;
5613
5614  // Don't descend into unevaluated contexts.
5615  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
5616
5617  // Now just recurse over the expression's children.
5618  CC = E->getExprLoc();
5619  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5620  bool IsLogicalOperator = BO && BO->isLogicalOp();
5621  for (Stmt::child_range I = E->children(); I; ++I) {
5622    Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
5623    if (!ChildExpr)
5624      continue;
5625
5626    if (IsLogicalOperator &&
5627        isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5628      // Ignore checking string literals that are in logical operators.
5629      continue;
5630    AnalyzeImplicitConversions(S, ChildExpr, CC);
5631  }
5632}
5633
5634} // end anonymous namespace
5635
5636/// Diagnoses "dangerous" implicit conversions within the given
5637/// expression (which is a full expression).  Implements -Wconversion
5638/// and -Wsign-compare.
5639///
5640/// \param CC the "context" location of the implicit conversion, i.e.
5641///   the most location of the syntactic entity requiring the implicit
5642///   conversion
5643void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
5644  // Don't diagnose in unevaluated contexts.
5645  if (isUnevaluatedContext())
5646    return;
5647
5648  // Don't diagnose for value- or type-dependent expressions.
5649  if (E->isTypeDependent() || E->isValueDependent())
5650    return;
5651
5652  // Check for array bounds violations in cases where the check isn't triggered
5653  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5654  // ArraySubscriptExpr is on the RHS of a variable initialization.
5655  CheckArrayAccess(E);
5656
5657  // This is not the right CC for (e.g.) a variable initialization.
5658  AnalyzeImplicitConversions(*this, E, CC);
5659}
5660
5661/// Diagnose when expression is an integer constant expression and its evaluation
5662/// results in integer overflow
5663void Sema::CheckForIntOverflow (Expr *E) {
5664  if (isa<BinaryOperator>(E->IgnoreParens()))
5665    E->EvaluateForOverflow(Context);
5666}
5667
5668namespace {
5669/// \brief Visitor for expressions which looks for unsequenced operations on the
5670/// same object.
5671class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5672  typedef EvaluatedExprVisitor<SequenceChecker> Base;
5673
5674  /// \brief A tree of sequenced regions within an expression. Two regions are
5675  /// unsequenced if one is an ancestor or a descendent of the other. When we
5676  /// finish processing an expression with sequencing, such as a comma
5677  /// expression, we fold its tree nodes into its parent, since they are
5678  /// unsequenced with respect to nodes we will visit later.
5679  class SequenceTree {
5680    struct Value {
5681      explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5682      unsigned Parent : 31;
5683      bool Merged : 1;
5684    };
5685    SmallVector<Value, 8> Values;
5686
5687  public:
5688    /// \brief A region within an expression which may be sequenced with respect
5689    /// to some other region.
5690    class Seq {
5691      explicit Seq(unsigned N) : Index(N) {}
5692      unsigned Index;
5693      friend class SequenceTree;
5694    public:
5695      Seq() : Index(0) {}
5696    };
5697
5698    SequenceTree() { Values.push_back(Value(0)); }
5699    Seq root() const { return Seq(0); }
5700
5701    /// \brief Create a new sequence of operations, which is an unsequenced
5702    /// subset of \p Parent. This sequence of operations is sequenced with
5703    /// respect to other children of \p Parent.
5704    Seq allocate(Seq Parent) {
5705      Values.push_back(Value(Parent.Index));
5706      return Seq(Values.size() - 1);
5707    }
5708
5709    /// \brief Merge a sequence of operations into its parent.
5710    void merge(Seq S) {
5711      Values[S.Index].Merged = true;
5712    }
5713
5714    /// \brief Determine whether two operations are unsequenced. This operation
5715    /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5716    /// should have been merged into its parent as appropriate.
5717    bool isUnsequenced(Seq Cur, Seq Old) {
5718      unsigned C = representative(Cur.Index);
5719      unsigned Target = representative(Old.Index);
5720      while (C >= Target) {
5721        if (C == Target)
5722          return true;
5723        C = Values[C].Parent;
5724      }
5725      return false;
5726    }
5727
5728  private:
5729    /// \brief Pick a representative for a sequence.
5730    unsigned representative(unsigned K) {
5731      if (Values[K].Merged)
5732        // Perform path compression as we go.
5733        return Values[K].Parent = representative(Values[K].Parent);
5734      return K;
5735    }
5736  };
5737
5738  /// An object for which we can track unsequenced uses.
5739  typedef NamedDecl *Object;
5740
5741  /// Different flavors of object usage which we track. We only track the
5742  /// least-sequenced usage of each kind.
5743  enum UsageKind {
5744    /// A read of an object. Multiple unsequenced reads are OK.
5745    UK_Use,
5746    /// A modification of an object which is sequenced before the value
5747    /// computation of the expression, such as ++n in C++.
5748    UK_ModAsValue,
5749    /// A modification of an object which is not sequenced before the value
5750    /// computation of the expression, such as n++.
5751    UK_ModAsSideEffect,
5752
5753    UK_Count = UK_ModAsSideEffect + 1
5754  };
5755
5756  struct Usage {
5757    Usage() : Use(0), Seq() {}
5758    Expr *Use;
5759    SequenceTree::Seq Seq;
5760  };
5761
5762  struct UsageInfo {
5763    UsageInfo() : Diagnosed(false) {}
5764    Usage Uses[UK_Count];
5765    /// Have we issued a diagnostic for this variable already?
5766    bool Diagnosed;
5767  };
5768  typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5769
5770  Sema &SemaRef;
5771  /// Sequenced regions within the expression.
5772  SequenceTree Tree;
5773  /// Declaration modifications and references which we have seen.
5774  UsageInfoMap UsageMap;
5775  /// The region we are currently within.
5776  SequenceTree::Seq Region;
5777  /// Filled in with declarations which were modified as a side-effect
5778  /// (that is, post-increment operations).
5779  SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
5780  /// Expressions to check later. We defer checking these to reduce
5781  /// stack usage.
5782  SmallVectorImpl<Expr *> &WorkList;
5783
5784  /// RAII object wrapping the visitation of a sequenced subexpression of an
5785  /// expression. At the end of this process, the side-effects of the evaluation
5786  /// become sequenced with respect to the value computation of the result, so
5787  /// we downgrade any UK_ModAsSideEffect within the evaluation to
5788  /// UK_ModAsValue.
5789  struct SequencedSubexpression {
5790    SequencedSubexpression(SequenceChecker &Self)
5791      : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5792      Self.ModAsSideEffect = &ModAsSideEffect;
5793    }
5794    ~SequencedSubexpression() {
5795      for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5796        UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5797        U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5798        Self.addUsage(U, ModAsSideEffect[I].first,
5799                      ModAsSideEffect[I].second.Use, UK_ModAsValue);
5800      }
5801      Self.ModAsSideEffect = OldModAsSideEffect;
5802    }
5803
5804    SequenceChecker &Self;
5805    SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5806    SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5807  };
5808
5809  /// RAII object wrapping the visitation of a subexpression which we might
5810  /// choose to evaluate as a constant. If any subexpression is evaluated and
5811  /// found to be non-constant, this allows us to suppress the evaluation of
5812  /// the outer expression.
5813  class EvaluationTracker {
5814  public:
5815    EvaluationTracker(SequenceChecker &Self)
5816        : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5817      Self.EvalTracker = this;
5818    }
5819    ~EvaluationTracker() {
5820      Self.EvalTracker = Prev;
5821      if (Prev)
5822        Prev->EvalOK &= EvalOK;
5823    }
5824
5825    bool evaluate(const Expr *E, bool &Result) {
5826      if (!EvalOK || E->isValueDependent())
5827        return false;
5828      EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5829      return EvalOK;
5830    }
5831
5832  private:
5833    SequenceChecker &Self;
5834    EvaluationTracker *Prev;
5835    bool EvalOK;
5836  } *EvalTracker;
5837
5838  /// \brief Find the object which is produced by the specified expression,
5839  /// if any.
5840  Object getObject(Expr *E, bool Mod) const {
5841    E = E->IgnoreParenCasts();
5842    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5843      if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5844        return getObject(UO->getSubExpr(), Mod);
5845    } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5846      if (BO->getOpcode() == BO_Comma)
5847        return getObject(BO->getRHS(), Mod);
5848      if (Mod && BO->isAssignmentOp())
5849        return getObject(BO->getLHS(), Mod);
5850    } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5851      // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5852      if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5853        return ME->getMemberDecl();
5854    } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5855      // FIXME: If this is a reference, map through to its value.
5856      return DRE->getDecl();
5857    return 0;
5858  }
5859
5860  /// \brief Note that an object was modified or used by an expression.
5861  void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5862    Usage &U = UI.Uses[UK];
5863    if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5864      if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5865        ModAsSideEffect->push_back(std::make_pair(O, U));
5866      U.Use = Ref;
5867      U.Seq = Region;
5868    }
5869  }
5870  /// \brief Check whether a modification or use conflicts with a prior usage.
5871  void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5872                  bool IsModMod) {
5873    if (UI.Diagnosed)
5874      return;
5875
5876    const Usage &U = UI.Uses[OtherKind];
5877    if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5878      return;
5879
5880    Expr *Mod = U.Use;
5881    Expr *ModOrUse = Ref;
5882    if (OtherKind == UK_Use)
5883      std::swap(Mod, ModOrUse);
5884
5885    SemaRef.Diag(Mod->getExprLoc(),
5886                 IsModMod ? diag::warn_unsequenced_mod_mod
5887                          : diag::warn_unsequenced_mod_use)
5888      << O << SourceRange(ModOrUse->getExprLoc());
5889    UI.Diagnosed = true;
5890  }
5891
5892  void notePreUse(Object O, Expr *Use) {
5893    UsageInfo &U = UsageMap[O];
5894    // Uses conflict with other modifications.
5895    checkUsage(O, U, Use, UK_ModAsValue, false);
5896  }
5897  void notePostUse(Object O, Expr *Use) {
5898    UsageInfo &U = UsageMap[O];
5899    checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5900    addUsage(U, O, Use, UK_Use);
5901  }
5902
5903  void notePreMod(Object O, Expr *Mod) {
5904    UsageInfo &U = UsageMap[O];
5905    // Modifications conflict with other modifications and with uses.
5906    checkUsage(O, U, Mod, UK_ModAsValue, true);
5907    checkUsage(O, U, Mod, UK_Use, false);
5908  }
5909  void notePostMod(Object O, Expr *Use, UsageKind UK) {
5910    UsageInfo &U = UsageMap[O];
5911    checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5912    addUsage(U, O, Use, UK);
5913  }
5914
5915public:
5916  SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5917      : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5918        WorkList(WorkList), EvalTracker(0) {
5919    Visit(E);
5920  }
5921
5922  void VisitStmt(Stmt *S) {
5923    // Skip all statements which aren't expressions for now.
5924  }
5925
5926  void VisitExpr(Expr *E) {
5927    // By default, just recurse to evaluated subexpressions.
5928    Base::VisitStmt(E);
5929  }
5930
5931  void VisitCastExpr(CastExpr *E) {
5932    Object O = Object();
5933    if (E->getCastKind() == CK_LValueToRValue)
5934      O = getObject(E->getSubExpr(), false);
5935
5936    if (O)
5937      notePreUse(O, E);
5938    VisitExpr(E);
5939    if (O)
5940      notePostUse(O, E);
5941  }
5942
5943  void VisitBinComma(BinaryOperator *BO) {
5944    // C++11 [expr.comma]p1:
5945    //   Every value computation and side effect associated with the left
5946    //   expression is sequenced before every value computation and side
5947    //   effect associated with the right expression.
5948    SequenceTree::Seq LHS = Tree.allocate(Region);
5949    SequenceTree::Seq RHS = Tree.allocate(Region);
5950    SequenceTree::Seq OldRegion = Region;
5951
5952    {
5953      SequencedSubexpression SeqLHS(*this);
5954      Region = LHS;
5955      Visit(BO->getLHS());
5956    }
5957
5958    Region = RHS;
5959    Visit(BO->getRHS());
5960
5961    Region = OldRegion;
5962
5963    // Forget that LHS and RHS are sequenced. They are both unsequenced
5964    // with respect to other stuff.
5965    Tree.merge(LHS);
5966    Tree.merge(RHS);
5967  }
5968
5969  void VisitBinAssign(BinaryOperator *BO) {
5970    // The modification is sequenced after the value computation of the LHS
5971    // and RHS, so check it before inspecting the operands and update the
5972    // map afterwards.
5973    Object O = getObject(BO->getLHS(), true);
5974    if (!O)
5975      return VisitExpr(BO);
5976
5977    notePreMod(O, BO);
5978
5979    // C++11 [expr.ass]p7:
5980    //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5981    //   only once.
5982    //
5983    // Therefore, for a compound assignment operator, O is considered used
5984    // everywhere except within the evaluation of E1 itself.
5985    if (isa<CompoundAssignOperator>(BO))
5986      notePreUse(O, BO);
5987
5988    Visit(BO->getLHS());
5989
5990    if (isa<CompoundAssignOperator>(BO))
5991      notePostUse(O, BO);
5992
5993    Visit(BO->getRHS());
5994
5995    // C++11 [expr.ass]p1:
5996    //   the assignment is sequenced [...] before the value computation of the
5997    //   assignment expression.
5998    // C11 6.5.16/3 has no such rule.
5999    notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6000                                                       : UK_ModAsSideEffect);
6001  }
6002  void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6003    VisitBinAssign(CAO);
6004  }
6005
6006  void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6007  void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6008  void VisitUnaryPreIncDec(UnaryOperator *UO) {
6009    Object O = getObject(UO->getSubExpr(), true);
6010    if (!O)
6011      return VisitExpr(UO);
6012
6013    notePreMod(O, UO);
6014    Visit(UO->getSubExpr());
6015    // C++11 [expr.pre.incr]p1:
6016    //   the expression ++x is equivalent to x+=1
6017    notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6018                                                       : UK_ModAsSideEffect);
6019  }
6020
6021  void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6022  void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6023  void VisitUnaryPostIncDec(UnaryOperator *UO) {
6024    Object O = getObject(UO->getSubExpr(), true);
6025    if (!O)
6026      return VisitExpr(UO);
6027
6028    notePreMod(O, UO);
6029    Visit(UO->getSubExpr());
6030    notePostMod(O, UO, UK_ModAsSideEffect);
6031  }
6032
6033  /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6034  void VisitBinLOr(BinaryOperator *BO) {
6035    // The side-effects of the LHS of an '&&' are sequenced before the
6036    // value computation of the RHS, and hence before the value computation
6037    // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6038    // as if they were unconditionally sequenced.
6039    EvaluationTracker Eval(*this);
6040    {
6041      SequencedSubexpression Sequenced(*this);
6042      Visit(BO->getLHS());
6043    }
6044
6045    bool Result;
6046    if (Eval.evaluate(BO->getLHS(), Result)) {
6047      if (!Result)
6048        Visit(BO->getRHS());
6049    } else {
6050      // Check for unsequenced operations in the RHS, treating it as an
6051      // entirely separate evaluation.
6052      //
6053      // FIXME: If there are operations in the RHS which are unsequenced
6054      // with respect to operations outside the RHS, and those operations
6055      // are unconditionally evaluated, diagnose them.
6056      WorkList.push_back(BO->getRHS());
6057    }
6058  }
6059  void VisitBinLAnd(BinaryOperator *BO) {
6060    EvaluationTracker Eval(*this);
6061    {
6062      SequencedSubexpression Sequenced(*this);
6063      Visit(BO->getLHS());
6064    }
6065
6066    bool Result;
6067    if (Eval.evaluate(BO->getLHS(), Result)) {
6068      if (Result)
6069        Visit(BO->getRHS());
6070    } else {
6071      WorkList.push_back(BO->getRHS());
6072    }
6073  }
6074
6075  // Only visit the condition, unless we can be sure which subexpression will
6076  // be chosen.
6077  void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
6078    EvaluationTracker Eval(*this);
6079    {
6080      SequencedSubexpression Sequenced(*this);
6081      Visit(CO->getCond());
6082    }
6083
6084    bool Result;
6085    if (Eval.evaluate(CO->getCond(), Result))
6086      Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
6087    else {
6088      WorkList.push_back(CO->getTrueExpr());
6089      WorkList.push_back(CO->getFalseExpr());
6090    }
6091  }
6092
6093  void VisitCallExpr(CallExpr *CE) {
6094    // C++11 [intro.execution]p15:
6095    //   When calling a function [...], every value computation and side effect
6096    //   associated with any argument expression, or with the postfix expression
6097    //   designating the called function, is sequenced before execution of every
6098    //   expression or statement in the body of the function [and thus before
6099    //   the value computation of its result].
6100    SequencedSubexpression Sequenced(*this);
6101    Base::VisitCallExpr(CE);
6102
6103    // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6104  }
6105
6106  void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
6107    // This is a call, so all subexpressions are sequenced before the result.
6108    SequencedSubexpression Sequenced(*this);
6109
6110    if (!CCE->isListInitialization())
6111      return VisitExpr(CCE);
6112
6113    // In C++11, list initializations are sequenced.
6114    SmallVector<SequenceTree::Seq, 32> Elts;
6115    SequenceTree::Seq Parent = Region;
6116    for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6117                                        E = CCE->arg_end();
6118         I != E; ++I) {
6119      Region = Tree.allocate(Parent);
6120      Elts.push_back(Region);
6121      Visit(*I);
6122    }
6123
6124    // Forget that the initializers are sequenced.
6125    Region = Parent;
6126    for (unsigned I = 0; I < Elts.size(); ++I)
6127      Tree.merge(Elts[I]);
6128  }
6129
6130  void VisitInitListExpr(InitListExpr *ILE) {
6131    if (!SemaRef.getLangOpts().CPlusPlus11)
6132      return VisitExpr(ILE);
6133
6134    // In C++11, list initializations are sequenced.
6135    SmallVector<SequenceTree::Seq, 32> Elts;
6136    SequenceTree::Seq Parent = Region;
6137    for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6138      Expr *E = ILE->getInit(I);
6139      if (!E) continue;
6140      Region = Tree.allocate(Parent);
6141      Elts.push_back(Region);
6142      Visit(E);
6143    }
6144
6145    // Forget that the initializers are sequenced.
6146    Region = Parent;
6147    for (unsigned I = 0; I < Elts.size(); ++I)
6148      Tree.merge(Elts[I]);
6149  }
6150};
6151}
6152
6153void Sema::CheckUnsequencedOperations(Expr *E) {
6154  SmallVector<Expr *, 8> WorkList;
6155  WorkList.push_back(E);
6156  while (!WorkList.empty()) {
6157    Expr *Item = WorkList.pop_back_val();
6158    SequenceChecker(*this, Item, WorkList);
6159  }
6160}
6161
6162void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6163                              bool IsConstexpr) {
6164  CheckImplicitConversions(E, CheckLoc);
6165  CheckUnsequencedOperations(E);
6166  if (!IsConstexpr && !E->isValueDependent())
6167    CheckForIntOverflow(E);
6168}
6169
6170void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6171                                       FieldDecl *BitField,
6172                                       Expr *Init) {
6173  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6174}
6175
6176/// CheckParmsForFunctionDef - Check that the parameters of the given
6177/// function are appropriate for the definition of a function. This
6178/// takes care of any checks that cannot be performed on the
6179/// declaration itself, e.g., that the types of each of the function
6180/// parameters are complete.
6181bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6182                                    ParmVarDecl *const *PEnd,
6183                                    bool CheckParameterNames) {
6184  bool HasInvalidParm = false;
6185  for (; P != PEnd; ++P) {
6186    ParmVarDecl *Param = *P;
6187
6188    // C99 6.7.5.3p4: the parameters in a parameter type list in a
6189    // function declarator that is part of a function definition of
6190    // that function shall not have incomplete type.
6191    //
6192    // This is also C++ [dcl.fct]p6.
6193    if (!Param->isInvalidDecl() &&
6194        RequireCompleteType(Param->getLocation(), Param->getType(),
6195                            diag::err_typecheck_decl_incomplete_type)) {
6196      Param->setInvalidDecl();
6197      HasInvalidParm = true;
6198    }
6199
6200    // C99 6.9.1p5: If the declarator includes a parameter type list, the
6201    // declaration of each parameter shall include an identifier.
6202    if (CheckParameterNames &&
6203        Param->getIdentifier() == 0 &&
6204        !Param->isImplicit() &&
6205        !getLangOpts().CPlusPlus)
6206      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6207
6208    // C99 6.7.5.3p12:
6209    //   If the function declarator is not part of a definition of that
6210    //   function, parameters may have incomplete type and may use the [*]
6211    //   notation in their sequences of declarator specifiers to specify
6212    //   variable length array types.
6213    QualType PType = Param->getOriginalType();
6214    while (const ArrayType *AT = Context.getAsArrayType(PType)) {
6215      if (AT->getSizeModifier() == ArrayType::Star) {
6216        // FIXME: This diagnostic should point the '[*]' if source-location
6217        // information is added for it.
6218        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
6219        break;
6220      }
6221      PType= AT->getElementType();
6222    }
6223
6224    // MSVC destroys objects passed by value in the callee.  Therefore a
6225    // function definition which takes such a parameter must be able to call the
6226    // object's destructor.
6227    if (getLangOpts().CPlusPlus &&
6228        Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6229      if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6230        FinalizeVarWithDestructor(Param, RT);
6231    }
6232  }
6233
6234  return HasInvalidParm;
6235}
6236
6237/// CheckCastAlign - Implements -Wcast-align, which warns when a
6238/// pointer cast increases the alignment requirements.
6239void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6240  // This is actually a lot of work to potentially be doing on every
6241  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
6242  if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6243                                          TRange.getBegin())
6244        == DiagnosticsEngine::Ignored)
6245    return;
6246
6247  // Ignore dependent types.
6248  if (T->isDependentType() || Op->getType()->isDependentType())
6249    return;
6250
6251  // Require that the destination be a pointer type.
6252  const PointerType *DestPtr = T->getAs<PointerType>();
6253  if (!DestPtr) return;
6254
6255  // If the destination has alignment 1, we're done.
6256  QualType DestPointee = DestPtr->getPointeeType();
6257  if (DestPointee->isIncompleteType()) return;
6258  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6259  if (DestAlign.isOne()) return;
6260
6261  // Require that the source be a pointer type.
6262  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6263  if (!SrcPtr) return;
6264  QualType SrcPointee = SrcPtr->getPointeeType();
6265
6266  // Whitelist casts from cv void*.  We already implicitly
6267  // whitelisted casts to cv void*, since they have alignment 1.
6268  // Also whitelist casts involving incomplete types, which implicitly
6269  // includes 'void'.
6270  if (SrcPointee->isIncompleteType()) return;
6271
6272  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6273  if (SrcAlign >= DestAlign) return;
6274
6275  Diag(TRange.getBegin(), diag::warn_cast_align)
6276    << Op->getType() << T
6277    << static_cast<unsigned>(SrcAlign.getQuantity())
6278    << static_cast<unsigned>(DestAlign.getQuantity())
6279    << TRange << Op->getSourceRange();
6280}
6281
6282static const Type* getElementType(const Expr *BaseExpr) {
6283  const Type* EltType = BaseExpr->getType().getTypePtr();
6284  if (EltType->isAnyPointerType())
6285    return EltType->getPointeeType().getTypePtr();
6286  else if (EltType->isArrayType())
6287    return EltType->getBaseElementTypeUnsafe();
6288  return EltType;
6289}
6290
6291/// \brief Check whether this array fits the idiom of a size-one tail padded
6292/// array member of a struct.
6293///
6294/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6295/// commonly used to emulate flexible arrays in C89 code.
6296static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6297                                    const NamedDecl *ND) {
6298  if (Size != 1 || !ND) return false;
6299
6300  const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6301  if (!FD) return false;
6302
6303  // Don't consider sizes resulting from macro expansions or template argument
6304  // substitution to form C89 tail-padded arrays.
6305
6306  TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
6307  while (TInfo) {
6308    TypeLoc TL = TInfo->getTypeLoc();
6309    // Look through typedefs.
6310    if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6311      const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
6312      TInfo = TDL->getTypeSourceInfo();
6313      continue;
6314    }
6315    if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6316      const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
6317      if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6318        return false;
6319    }
6320    break;
6321  }
6322
6323  const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
6324  if (!RD) return false;
6325  if (RD->isUnion()) return false;
6326  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6327    if (!CRD->isStandardLayout()) return false;
6328  }
6329
6330  // See if this is the last field decl in the record.
6331  const Decl *D = FD;
6332  while ((D = D->getNextDeclInContext()))
6333    if (isa<FieldDecl>(D))
6334      return false;
6335  return true;
6336}
6337
6338void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
6339                            const ArraySubscriptExpr *ASE,
6340                            bool AllowOnePastEnd, bool IndexNegated) {
6341  IndexExpr = IndexExpr->IgnoreParenImpCasts();
6342  if (IndexExpr->isValueDependent())
6343    return;
6344
6345  const Type *EffectiveType = getElementType(BaseExpr);
6346  BaseExpr = BaseExpr->IgnoreParenCasts();
6347  const ConstantArrayType *ArrayTy =
6348    Context.getAsConstantArrayType(BaseExpr->getType());
6349  if (!ArrayTy)
6350    return;
6351
6352  llvm::APSInt index;
6353  if (!IndexExpr->EvaluateAsInt(index, Context))
6354    return;
6355  if (IndexNegated)
6356    index = -index;
6357
6358  const NamedDecl *ND = NULL;
6359  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6360    ND = dyn_cast<NamedDecl>(DRE->getDecl());
6361  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6362    ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6363
6364  if (index.isUnsigned() || !index.isNegative()) {
6365    llvm::APInt size = ArrayTy->getSize();
6366    if (!size.isStrictlyPositive())
6367      return;
6368
6369    const Type* BaseType = getElementType(BaseExpr);
6370    if (BaseType != EffectiveType) {
6371      // Make sure we're comparing apples to apples when comparing index to size
6372      uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6373      uint64_t array_typesize = Context.getTypeSize(BaseType);
6374      // Handle ptrarith_typesize being zero, such as when casting to void*
6375      if (!ptrarith_typesize) ptrarith_typesize = 1;
6376      if (ptrarith_typesize != array_typesize) {
6377        // There's a cast to a different size type involved
6378        uint64_t ratio = array_typesize / ptrarith_typesize;
6379        // TODO: Be smarter about handling cases where array_typesize is not a
6380        // multiple of ptrarith_typesize
6381        if (ptrarith_typesize * ratio == array_typesize)
6382          size *= llvm::APInt(size.getBitWidth(), ratio);
6383      }
6384    }
6385
6386    if (size.getBitWidth() > index.getBitWidth())
6387      index = index.zext(size.getBitWidth());
6388    else if (size.getBitWidth() < index.getBitWidth())
6389      size = size.zext(index.getBitWidth());
6390
6391    // For array subscripting the index must be less than size, but for pointer
6392    // arithmetic also allow the index (offset) to be equal to size since
6393    // computing the next address after the end of the array is legal and
6394    // commonly done e.g. in C++ iterators and range-based for loops.
6395    if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
6396      return;
6397
6398    // Also don't warn for arrays of size 1 which are members of some
6399    // structure. These are often used to approximate flexible arrays in C89
6400    // code.
6401    if (IsTailPaddedMemberArray(*this, size, ND))
6402      return;
6403
6404    // Suppress the warning if the subscript expression (as identified by the
6405    // ']' location) and the index expression are both from macro expansions
6406    // within a system header.
6407    if (ASE) {
6408      SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6409          ASE->getRBracketLoc());
6410      if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6411        SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6412            IndexExpr->getLocStart());
6413        if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
6414          return;
6415      }
6416    }
6417
6418    unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
6419    if (ASE)
6420      DiagID = diag::warn_array_index_exceeds_bounds;
6421
6422    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6423                        PDiag(DiagID) << index.toString(10, true)
6424                          << size.toString(10, true)
6425                          << (unsigned)size.getLimitedValue(~0U)
6426                          << IndexExpr->getSourceRange());
6427  } else {
6428    unsigned DiagID = diag::warn_array_index_precedes_bounds;
6429    if (!ASE) {
6430      DiagID = diag::warn_ptr_arith_precedes_bounds;
6431      if (index.isNegative()) index = -index;
6432    }
6433
6434    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6435                        PDiag(DiagID) << index.toString(10, true)
6436                          << IndexExpr->getSourceRange());
6437  }
6438
6439  if (!ND) {
6440    // Try harder to find a NamedDecl to point at in the note.
6441    while (const ArraySubscriptExpr *ASE =
6442           dyn_cast<ArraySubscriptExpr>(BaseExpr))
6443      BaseExpr = ASE->getBase()->IgnoreParenCasts();
6444    if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6445      ND = dyn_cast<NamedDecl>(DRE->getDecl());
6446    if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6447      ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6448  }
6449
6450  if (ND)
6451    DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6452                        PDiag(diag::note_array_index_out_of_bounds)
6453                          << ND->getDeclName());
6454}
6455
6456void Sema::CheckArrayAccess(const Expr *expr) {
6457  int AllowOnePastEnd = 0;
6458  while (expr) {
6459    expr = expr->IgnoreParenImpCasts();
6460    switch (expr->getStmtClass()) {
6461      case Stmt::ArraySubscriptExprClass: {
6462        const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
6463        CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
6464                         AllowOnePastEnd > 0);
6465        return;
6466      }
6467      case Stmt::UnaryOperatorClass: {
6468        // Only unwrap the * and & unary operators
6469        const UnaryOperator *UO = cast<UnaryOperator>(expr);
6470        expr = UO->getSubExpr();
6471        switch (UO->getOpcode()) {
6472          case UO_AddrOf:
6473            AllowOnePastEnd++;
6474            break;
6475          case UO_Deref:
6476            AllowOnePastEnd--;
6477            break;
6478          default:
6479            return;
6480        }
6481        break;
6482      }
6483      case Stmt::ConditionalOperatorClass: {
6484        const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6485        if (const Expr *lhs = cond->getLHS())
6486          CheckArrayAccess(lhs);
6487        if (const Expr *rhs = cond->getRHS())
6488          CheckArrayAccess(rhs);
6489        return;
6490      }
6491      default:
6492        return;
6493    }
6494  }
6495}
6496
6497//===--- CHECK: Objective-C retain cycles ----------------------------------//
6498
6499namespace {
6500  struct RetainCycleOwner {
6501    RetainCycleOwner() : Variable(0), Indirect(false) {}
6502    VarDecl *Variable;
6503    SourceRange Range;
6504    SourceLocation Loc;
6505    bool Indirect;
6506
6507    void setLocsFrom(Expr *e) {
6508      Loc = e->getExprLoc();
6509      Range = e->getSourceRange();
6510    }
6511  };
6512}
6513
6514/// Consider whether capturing the given variable can possibly lead to
6515/// a retain cycle.
6516static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
6517  // In ARC, it's captured strongly iff the variable has __strong
6518  // lifetime.  In MRR, it's captured strongly if the variable is
6519  // __block and has an appropriate type.
6520  if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6521    return false;
6522
6523  owner.Variable = var;
6524  if (ref)
6525    owner.setLocsFrom(ref);
6526  return true;
6527}
6528
6529static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
6530  while (true) {
6531    e = e->IgnoreParens();
6532    if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6533      switch (cast->getCastKind()) {
6534      case CK_BitCast:
6535      case CK_LValueBitCast:
6536      case CK_LValueToRValue:
6537      case CK_ARCReclaimReturnedObject:
6538        e = cast->getSubExpr();
6539        continue;
6540
6541      default:
6542        return false;
6543      }
6544    }
6545
6546    if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6547      ObjCIvarDecl *ivar = ref->getDecl();
6548      if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6549        return false;
6550
6551      // Try to find a retain cycle in the base.
6552      if (!findRetainCycleOwner(S, ref->getBase(), owner))
6553        return false;
6554
6555      if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6556      owner.Indirect = true;
6557      return true;
6558    }
6559
6560    if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6561      VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6562      if (!var) return false;
6563      return considerVariable(var, ref, owner);
6564    }
6565
6566    if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6567      if (member->isArrow()) return false;
6568
6569      // Don't count this as an indirect ownership.
6570      e = member->getBase();
6571      continue;
6572    }
6573
6574    if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6575      // Only pay attention to pseudo-objects on property references.
6576      ObjCPropertyRefExpr *pre
6577        = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6578                                              ->IgnoreParens());
6579      if (!pre) return false;
6580      if (pre->isImplicitProperty()) return false;
6581      ObjCPropertyDecl *property = pre->getExplicitProperty();
6582      if (!property->isRetaining() &&
6583          !(property->getPropertyIvarDecl() &&
6584            property->getPropertyIvarDecl()->getType()
6585              .getObjCLifetime() == Qualifiers::OCL_Strong))
6586          return false;
6587
6588      owner.Indirect = true;
6589      if (pre->isSuperReceiver()) {
6590        owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6591        if (!owner.Variable)
6592          return false;
6593        owner.Loc = pre->getLocation();
6594        owner.Range = pre->getSourceRange();
6595        return true;
6596      }
6597      e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6598                              ->getSourceExpr());
6599      continue;
6600    }
6601
6602    // Array ivars?
6603
6604    return false;
6605  }
6606}
6607
6608namespace {
6609  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6610    FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6611      : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6612        Variable(variable), Capturer(0) {}
6613
6614    VarDecl *Variable;
6615    Expr *Capturer;
6616
6617    void VisitDeclRefExpr(DeclRefExpr *ref) {
6618      if (ref->getDecl() == Variable && !Capturer)
6619        Capturer = ref;
6620    }
6621
6622    void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6623      if (Capturer) return;
6624      Visit(ref->getBase());
6625      if (Capturer && ref->isFreeIvar())
6626        Capturer = ref;
6627    }
6628
6629    void VisitBlockExpr(BlockExpr *block) {
6630      // Look inside nested blocks
6631      if (block->getBlockDecl()->capturesVariable(Variable))
6632        Visit(block->getBlockDecl()->getBody());
6633    }
6634
6635    void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6636      if (Capturer) return;
6637      if (OVE->getSourceExpr())
6638        Visit(OVE->getSourceExpr());
6639    }
6640  };
6641}
6642
6643/// Check whether the given argument is a block which captures a
6644/// variable.
6645static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6646  assert(owner.Variable && owner.Loc.isValid());
6647
6648  e = e->IgnoreParenCasts();
6649
6650  // Look through [^{...} copy] and Block_copy(^{...}).
6651  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6652    Selector Cmd = ME->getSelector();
6653    if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6654      e = ME->getInstanceReceiver();
6655      if (!e)
6656        return 0;
6657      e = e->IgnoreParenCasts();
6658    }
6659  } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6660    if (CE->getNumArgs() == 1) {
6661      FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
6662      if (Fn) {
6663        const IdentifierInfo *FnI = Fn->getIdentifier();
6664        if (FnI && FnI->isStr("_Block_copy")) {
6665          e = CE->getArg(0)->IgnoreParenCasts();
6666        }
6667      }
6668    }
6669  }
6670
6671  BlockExpr *block = dyn_cast<BlockExpr>(e);
6672  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6673    return 0;
6674
6675  FindCaptureVisitor visitor(S.Context, owner.Variable);
6676  visitor.Visit(block->getBlockDecl()->getBody());
6677  return visitor.Capturer;
6678}
6679
6680static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6681                                RetainCycleOwner &owner) {
6682  assert(capturer);
6683  assert(owner.Variable && owner.Loc.isValid());
6684
6685  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6686    << owner.Variable << capturer->getSourceRange();
6687  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6688    << owner.Indirect << owner.Range;
6689}
6690
6691/// Check for a keyword selector that starts with the word 'add' or
6692/// 'set'.
6693static bool isSetterLikeSelector(Selector sel) {
6694  if (sel.isUnarySelector()) return false;
6695
6696  StringRef str = sel.getNameForSlot(0);
6697  while (!str.empty() && str.front() == '_') str = str.substr(1);
6698  if (str.startswith("set"))
6699    str = str.substr(3);
6700  else if (str.startswith("add")) {
6701    // Specially whitelist 'addOperationWithBlock:'.
6702    if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6703      return false;
6704    str = str.substr(3);
6705  }
6706  else
6707    return false;
6708
6709  if (str.empty()) return true;
6710  return !isLowercase(str.front());
6711}
6712
6713/// Check a message send to see if it's likely to cause a retain cycle.
6714void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6715  // Only check instance methods whose selector looks like a setter.
6716  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6717    return;
6718
6719  // Try to find a variable that the receiver is strongly owned by.
6720  RetainCycleOwner owner;
6721  if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
6722    if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
6723      return;
6724  } else {
6725    assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6726    owner.Variable = getCurMethodDecl()->getSelfDecl();
6727    owner.Loc = msg->getSuperLoc();
6728    owner.Range = msg->getSuperLoc();
6729  }
6730
6731  // Check whether the receiver is captured by any of the arguments.
6732  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6733    if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6734      return diagnoseRetainCycle(*this, capturer, owner);
6735}
6736
6737/// Check a property assign to see if it's likely to cause a retain cycle.
6738void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6739  RetainCycleOwner owner;
6740  if (!findRetainCycleOwner(*this, receiver, owner))
6741    return;
6742
6743  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6744    diagnoseRetainCycle(*this, capturer, owner);
6745}
6746
6747void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6748  RetainCycleOwner Owner;
6749  if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6750    return;
6751
6752  // Because we don't have an expression for the variable, we have to set the
6753  // location explicitly here.
6754  Owner.Loc = Var->getLocation();
6755  Owner.Range = Var->getSourceRange();
6756
6757  if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6758    diagnoseRetainCycle(*this, Capturer, Owner);
6759}
6760
6761static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6762                                     Expr *RHS, bool isProperty) {
6763  // Check if RHS is an Objective-C object literal, which also can get
6764  // immediately zapped in a weak reference.  Note that we explicitly
6765  // allow ObjCStringLiterals, since those are designed to never really die.
6766  RHS = RHS->IgnoreParenImpCasts();
6767
6768  // This enum needs to match with the 'select' in
6769  // warn_objc_arc_literal_assign (off-by-1).
6770  Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6771  if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6772    return false;
6773
6774  S.Diag(Loc, diag::warn_arc_literal_assign)
6775    << (unsigned) Kind
6776    << (isProperty ? 0 : 1)
6777    << RHS->getSourceRange();
6778
6779  return true;
6780}
6781
6782static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6783                                    Qualifiers::ObjCLifetime LT,
6784                                    Expr *RHS, bool isProperty) {
6785  // Strip off any implicit cast added to get to the one ARC-specific.
6786  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6787    if (cast->getCastKind() == CK_ARCConsumeObject) {
6788      S.Diag(Loc, diag::warn_arc_retained_assign)
6789        << (LT == Qualifiers::OCL_ExplicitNone)
6790        << (isProperty ? 0 : 1)
6791        << RHS->getSourceRange();
6792      return true;
6793    }
6794    RHS = cast->getSubExpr();
6795  }
6796
6797  if (LT == Qualifiers::OCL_Weak &&
6798      checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6799    return true;
6800
6801  return false;
6802}
6803
6804bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6805                              QualType LHS, Expr *RHS) {
6806  Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6807
6808  if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6809    return false;
6810
6811  if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6812    return true;
6813
6814  return false;
6815}
6816
6817void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6818                              Expr *LHS, Expr *RHS) {
6819  QualType LHSType;
6820  // PropertyRef on LHS type need be directly obtained from
6821  // its declaration as it has a PsuedoType.
6822  ObjCPropertyRefExpr *PRE
6823    = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6824  if (PRE && !PRE->isImplicitProperty()) {
6825    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6826    if (PD)
6827      LHSType = PD->getType();
6828  }
6829
6830  if (LHSType.isNull())
6831    LHSType = LHS->getType();
6832
6833  Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6834
6835  if (LT == Qualifiers::OCL_Weak) {
6836    DiagnosticsEngine::Level Level =
6837      Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6838    if (Level != DiagnosticsEngine::Ignored)
6839      getCurFunction()->markSafeWeakUse(LHS);
6840  }
6841
6842  if (checkUnsafeAssigns(Loc, LHSType, RHS))
6843    return;
6844
6845  // FIXME. Check for other life times.
6846  if (LT != Qualifiers::OCL_None)
6847    return;
6848
6849  if (PRE) {
6850    if (PRE->isImplicitProperty())
6851      return;
6852    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6853    if (!PD)
6854      return;
6855
6856    unsigned Attributes = PD->getPropertyAttributes();
6857    if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
6858      // when 'assign' attribute was not explicitly specified
6859      // by user, ignore it and rely on property type itself
6860      // for lifetime info.
6861      unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6862      if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6863          LHSType->isObjCRetainableType())
6864        return;
6865
6866      while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6867        if (cast->getCastKind() == CK_ARCConsumeObject) {
6868          Diag(Loc, diag::warn_arc_retained_property_assign)
6869          << RHS->getSourceRange();
6870          return;
6871        }
6872        RHS = cast->getSubExpr();
6873      }
6874    }
6875    else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
6876      if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6877        return;
6878    }
6879  }
6880}
6881
6882//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6883
6884namespace {
6885bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6886                                 SourceLocation StmtLoc,
6887                                 const NullStmt *Body) {
6888  // Do not warn if the body is a macro that expands to nothing, e.g:
6889  //
6890  // #define CALL(x)
6891  // if (condition)
6892  //   CALL(0);
6893  //
6894  if (Body->hasLeadingEmptyMacro())
6895    return false;
6896
6897  // Get line numbers of statement and body.
6898  bool StmtLineInvalid;
6899  unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6900                                                      &StmtLineInvalid);
6901  if (StmtLineInvalid)
6902    return false;
6903
6904  bool BodyLineInvalid;
6905  unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6906                                                      &BodyLineInvalid);
6907  if (BodyLineInvalid)
6908    return false;
6909
6910  // Warn if null statement and body are on the same line.
6911  if (StmtLine != BodyLine)
6912    return false;
6913
6914  return true;
6915}
6916} // Unnamed namespace
6917
6918void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6919                                 const Stmt *Body,
6920                                 unsigned DiagID) {
6921  // Since this is a syntactic check, don't emit diagnostic for template
6922  // instantiations, this just adds noise.
6923  if (CurrentInstantiationScope)
6924    return;
6925
6926  // The body should be a null statement.
6927  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6928  if (!NBody)
6929    return;
6930
6931  // Do the usual checks.
6932  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6933    return;
6934
6935  Diag(NBody->getSemiLoc(), DiagID);
6936  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6937}
6938
6939void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6940                                 const Stmt *PossibleBody) {
6941  assert(!CurrentInstantiationScope); // Ensured by caller
6942
6943  SourceLocation StmtLoc;
6944  const Stmt *Body;
6945  unsigned DiagID;
6946  if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6947    StmtLoc = FS->getRParenLoc();
6948    Body = FS->getBody();
6949    DiagID = diag::warn_empty_for_body;
6950  } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6951    StmtLoc = WS->getCond()->getSourceRange().getEnd();
6952    Body = WS->getBody();
6953    DiagID = diag::warn_empty_while_body;
6954  } else
6955    return; // Neither `for' nor `while'.
6956
6957  // The body should be a null statement.
6958  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6959  if (!NBody)
6960    return;
6961
6962  // Skip expensive checks if diagnostic is disabled.
6963  if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6964          DiagnosticsEngine::Ignored)
6965    return;
6966
6967  // Do the usual checks.
6968  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6969    return;
6970
6971  // `for(...);' and `while(...);' are popular idioms, so in order to keep
6972  // noise level low, emit diagnostics only if for/while is followed by a
6973  // CompoundStmt, e.g.:
6974  //    for (int i = 0; i < n; i++);
6975  //    {
6976  //      a(i);
6977  //    }
6978  // or if for/while is followed by a statement with more indentation
6979  // than for/while itself:
6980  //    for (int i = 0; i < n; i++);
6981  //      a(i);
6982  bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6983  if (!ProbableTypo) {
6984    bool BodyColInvalid;
6985    unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6986                             PossibleBody->getLocStart(),
6987                             &BodyColInvalid);
6988    if (BodyColInvalid)
6989      return;
6990
6991    bool StmtColInvalid;
6992    unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6993                             S->getLocStart(),
6994                             &StmtColInvalid);
6995    if (StmtColInvalid)
6996      return;
6997
6998    if (BodyCol > StmtCol)
6999      ProbableTypo = true;
7000  }
7001
7002  if (ProbableTypo) {
7003    Diag(NBody->getSemiLoc(), DiagID);
7004    Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7005  }
7006}
7007
7008//===--- Layout compatibility ----------------------------------------------//
7009
7010namespace {
7011
7012bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7013
7014/// \brief Check if two enumeration types are layout-compatible.
7015bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7016  // C++11 [dcl.enum] p8:
7017  // Two enumeration types are layout-compatible if they have the same
7018  // underlying type.
7019  return ED1->isComplete() && ED2->isComplete() &&
7020         C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7021}
7022
7023/// \brief Check if two fields are layout-compatible.
7024bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7025  if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7026    return false;
7027
7028  if (Field1->isBitField() != Field2->isBitField())
7029    return false;
7030
7031  if (Field1->isBitField()) {
7032    // Make sure that the bit-fields are the same length.
7033    unsigned Bits1 = Field1->getBitWidthValue(C);
7034    unsigned Bits2 = Field2->getBitWidthValue(C);
7035
7036    if (Bits1 != Bits2)
7037      return false;
7038  }
7039
7040  return true;
7041}
7042
7043/// \brief Check if two standard-layout structs are layout-compatible.
7044/// (C++11 [class.mem] p17)
7045bool isLayoutCompatibleStruct(ASTContext &C,
7046                              RecordDecl *RD1,
7047                              RecordDecl *RD2) {
7048  // If both records are C++ classes, check that base classes match.
7049  if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7050    // If one of records is a CXXRecordDecl we are in C++ mode,
7051    // thus the other one is a CXXRecordDecl, too.
7052    const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7053    // Check number of base classes.
7054    if (D1CXX->getNumBases() != D2CXX->getNumBases())
7055      return false;
7056
7057    // Check the base classes.
7058    for (CXXRecordDecl::base_class_const_iterator
7059               Base1 = D1CXX->bases_begin(),
7060           BaseEnd1 = D1CXX->bases_end(),
7061              Base2 = D2CXX->bases_begin();
7062         Base1 != BaseEnd1;
7063         ++Base1, ++Base2) {
7064      if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7065        return false;
7066    }
7067  } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7068    // If only RD2 is a C++ class, it should have zero base classes.
7069    if (D2CXX->getNumBases() > 0)
7070      return false;
7071  }
7072
7073  // Check the fields.
7074  RecordDecl::field_iterator Field2 = RD2->field_begin(),
7075                             Field2End = RD2->field_end(),
7076                             Field1 = RD1->field_begin(),
7077                             Field1End = RD1->field_end();
7078  for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7079    if (!isLayoutCompatible(C, *Field1, *Field2))
7080      return false;
7081  }
7082  if (Field1 != Field1End || Field2 != Field2End)
7083    return false;
7084
7085  return true;
7086}
7087
7088/// \brief Check if two standard-layout unions are layout-compatible.
7089/// (C++11 [class.mem] p18)
7090bool isLayoutCompatibleUnion(ASTContext &C,
7091                             RecordDecl *RD1,
7092                             RecordDecl *RD2) {
7093  llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7094  for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7095                                  Field2End = RD2->field_end();
7096       Field2 != Field2End; ++Field2) {
7097    UnmatchedFields.insert(*Field2);
7098  }
7099
7100  for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7101                                  Field1End = RD1->field_end();
7102       Field1 != Field1End; ++Field1) {
7103    llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7104        I = UnmatchedFields.begin(),
7105        E = UnmatchedFields.end();
7106
7107    for ( ; I != E; ++I) {
7108      if (isLayoutCompatible(C, *Field1, *I)) {
7109        bool Result = UnmatchedFields.erase(*I);
7110        (void) Result;
7111        assert(Result);
7112        break;
7113      }
7114    }
7115    if (I == E)
7116      return false;
7117  }
7118
7119  return UnmatchedFields.empty();
7120}
7121
7122bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7123  if (RD1->isUnion() != RD2->isUnion())
7124    return false;
7125
7126  if (RD1->isUnion())
7127    return isLayoutCompatibleUnion(C, RD1, RD2);
7128  else
7129    return isLayoutCompatibleStruct(C, RD1, RD2);
7130}
7131
7132/// \brief Check if two types are layout-compatible in C++11 sense.
7133bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7134  if (T1.isNull() || T2.isNull())
7135    return false;
7136
7137  // C++11 [basic.types] p11:
7138  // If two types T1 and T2 are the same type, then T1 and T2 are
7139  // layout-compatible types.
7140  if (C.hasSameType(T1, T2))
7141    return true;
7142
7143  T1 = T1.getCanonicalType().getUnqualifiedType();
7144  T2 = T2.getCanonicalType().getUnqualifiedType();
7145
7146  const Type::TypeClass TC1 = T1->getTypeClass();
7147  const Type::TypeClass TC2 = T2->getTypeClass();
7148
7149  if (TC1 != TC2)
7150    return false;
7151
7152  if (TC1 == Type::Enum) {
7153    return isLayoutCompatible(C,
7154                              cast<EnumType>(T1)->getDecl(),
7155                              cast<EnumType>(T2)->getDecl());
7156  } else if (TC1 == Type::Record) {
7157    if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7158      return false;
7159
7160    return isLayoutCompatible(C,
7161                              cast<RecordType>(T1)->getDecl(),
7162                              cast<RecordType>(T2)->getDecl());
7163  }
7164
7165  return false;
7166}
7167}
7168
7169//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7170
7171namespace {
7172/// \brief Given a type tag expression find the type tag itself.
7173///
7174/// \param TypeExpr Type tag expression, as it appears in user's code.
7175///
7176/// \param VD Declaration of an identifier that appears in a type tag.
7177///
7178/// \param MagicValue Type tag magic value.
7179bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7180                     const ValueDecl **VD, uint64_t *MagicValue) {
7181  while(true) {
7182    if (!TypeExpr)
7183      return false;
7184
7185    TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7186
7187    switch (TypeExpr->getStmtClass()) {
7188    case Stmt::UnaryOperatorClass: {
7189      const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7190      if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7191        TypeExpr = UO->getSubExpr();
7192        continue;
7193      }
7194      return false;
7195    }
7196
7197    case Stmt::DeclRefExprClass: {
7198      const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7199      *VD = DRE->getDecl();
7200      return true;
7201    }
7202
7203    case Stmt::IntegerLiteralClass: {
7204      const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7205      llvm::APInt MagicValueAPInt = IL->getValue();
7206      if (MagicValueAPInt.getActiveBits() <= 64) {
7207        *MagicValue = MagicValueAPInt.getZExtValue();
7208        return true;
7209      } else
7210        return false;
7211    }
7212
7213    case Stmt::BinaryConditionalOperatorClass:
7214    case Stmt::ConditionalOperatorClass: {
7215      const AbstractConditionalOperator *ACO =
7216          cast<AbstractConditionalOperator>(TypeExpr);
7217      bool Result;
7218      if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7219        if (Result)
7220          TypeExpr = ACO->getTrueExpr();
7221        else
7222          TypeExpr = ACO->getFalseExpr();
7223        continue;
7224      }
7225      return false;
7226    }
7227
7228    case Stmt::BinaryOperatorClass: {
7229      const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7230      if (BO->getOpcode() == BO_Comma) {
7231        TypeExpr = BO->getRHS();
7232        continue;
7233      }
7234      return false;
7235    }
7236
7237    default:
7238      return false;
7239    }
7240  }
7241}
7242
7243/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7244///
7245/// \param TypeExpr Expression that specifies a type tag.
7246///
7247/// \param MagicValues Registered magic values.
7248///
7249/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7250///        kind.
7251///
7252/// \param TypeInfo Information about the corresponding C type.
7253///
7254/// \returns true if the corresponding C type was found.
7255bool GetMatchingCType(
7256        const IdentifierInfo *ArgumentKind,
7257        const Expr *TypeExpr, const ASTContext &Ctx,
7258        const llvm::DenseMap<Sema::TypeTagMagicValue,
7259                             Sema::TypeTagData> *MagicValues,
7260        bool &FoundWrongKind,
7261        Sema::TypeTagData &TypeInfo) {
7262  FoundWrongKind = false;
7263
7264  // Variable declaration that has type_tag_for_datatype attribute.
7265  const ValueDecl *VD = NULL;
7266
7267  uint64_t MagicValue;
7268
7269  if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7270    return false;
7271
7272  if (VD) {
7273    for (specific_attr_iterator<TypeTagForDatatypeAttr>
7274             I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7275             E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7276         I != E; ++I) {
7277      if (I->getArgumentKind() != ArgumentKind) {
7278        FoundWrongKind = true;
7279        return false;
7280      }
7281      TypeInfo.Type = I->getMatchingCType();
7282      TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7283      TypeInfo.MustBeNull = I->getMustBeNull();
7284      return true;
7285    }
7286    return false;
7287  }
7288
7289  if (!MagicValues)
7290    return false;
7291
7292  llvm::DenseMap<Sema::TypeTagMagicValue,
7293                 Sema::TypeTagData>::const_iterator I =
7294      MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7295  if (I == MagicValues->end())
7296    return false;
7297
7298  TypeInfo = I->second;
7299  return true;
7300}
7301} // unnamed namespace
7302
7303void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7304                                      uint64_t MagicValue, QualType Type,
7305                                      bool LayoutCompatible,
7306                                      bool MustBeNull) {
7307  if (!TypeTagForDatatypeMagicValues)
7308    TypeTagForDatatypeMagicValues.reset(
7309        new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7310
7311  TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7312  (*TypeTagForDatatypeMagicValues)[Magic] =
7313      TypeTagData(Type, LayoutCompatible, MustBeNull);
7314}
7315
7316namespace {
7317bool IsSameCharType(QualType T1, QualType T2) {
7318  const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7319  if (!BT1)
7320    return false;
7321
7322  const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7323  if (!BT2)
7324    return false;
7325
7326  BuiltinType::Kind T1Kind = BT1->getKind();
7327  BuiltinType::Kind T2Kind = BT2->getKind();
7328
7329  return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
7330         (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
7331         (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7332         (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7333}
7334} // unnamed namespace
7335
7336void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7337                                    const Expr * const *ExprArgs) {
7338  const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7339  bool IsPointerAttr = Attr->getIsPointer();
7340
7341  const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7342  bool FoundWrongKind;
7343  TypeTagData TypeInfo;
7344  if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7345                        TypeTagForDatatypeMagicValues.get(),
7346                        FoundWrongKind, TypeInfo)) {
7347    if (FoundWrongKind)
7348      Diag(TypeTagExpr->getExprLoc(),
7349           diag::warn_type_tag_for_datatype_wrong_kind)
7350        << TypeTagExpr->getSourceRange();
7351    return;
7352  }
7353
7354  const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7355  if (IsPointerAttr) {
7356    // Skip implicit cast of pointer to `void *' (as a function argument).
7357    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
7358      if (ICE->getType()->isVoidPointerType() &&
7359          ICE->getCastKind() == CK_BitCast)
7360        ArgumentExpr = ICE->getSubExpr();
7361  }
7362  QualType ArgumentType = ArgumentExpr->getType();
7363
7364  // Passing a `void*' pointer shouldn't trigger a warning.
7365  if (IsPointerAttr && ArgumentType->isVoidPointerType())
7366    return;
7367
7368  if (TypeInfo.MustBeNull) {
7369    // Type tag with matching void type requires a null pointer.
7370    if (!ArgumentExpr->isNullPointerConstant(Context,
7371                                             Expr::NPC_ValueDependentIsNotNull)) {
7372      Diag(ArgumentExpr->getExprLoc(),
7373           diag::warn_type_safety_null_pointer_required)
7374          << ArgumentKind->getName()
7375          << ArgumentExpr->getSourceRange()
7376          << TypeTagExpr->getSourceRange();
7377    }
7378    return;
7379  }
7380
7381  QualType RequiredType = TypeInfo.Type;
7382  if (IsPointerAttr)
7383    RequiredType = Context.getPointerType(RequiredType);
7384
7385  bool mismatch = false;
7386  if (!TypeInfo.LayoutCompatible) {
7387    mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7388
7389    // C++11 [basic.fundamental] p1:
7390    // Plain char, signed char, and unsigned char are three distinct types.
7391    //
7392    // But we treat plain `char' as equivalent to `signed char' or `unsigned
7393    // char' depending on the current char signedness mode.
7394    if (mismatch)
7395      if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7396                                           RequiredType->getPointeeType())) ||
7397          (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7398        mismatch = false;
7399  } else
7400    if (IsPointerAttr)
7401      mismatch = !isLayoutCompatible(Context,
7402                                     ArgumentType->getPointeeType(),
7403                                     RequiredType->getPointeeType());
7404    else
7405      mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7406
7407  if (mismatch)
7408    Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7409        << ArgumentType << ArgumentKind->getName()
7410        << TypeInfo.LayoutCompatible << RequiredType
7411        << ArgumentExpr->getSourceRange()
7412        << TypeTagExpr->getSourceRange();
7413}
7414