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