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