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