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