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