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