SemaCast.cpp 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762
  1. //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
  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 semantic analysis for cast expressions, including
  11. // 1) C-style casts like '(int) x'
  12. // 2) C++ functional casts like 'int(x)'
  13. // 3) C++ named casts like 'static_cast<int>(x)'
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "clang/Sema/SemaInternal.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/AST/RecordLayout.h"
  22. #include "clang/Basic/PartialDiagnostic.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "clang/Lex/Preprocessor.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include <set>
  28. using namespace clang;
  29. enum TryCastResult {
  30. TC_NotApplicable, ///< The cast method is not applicable.
  31. TC_Success, ///< The cast method is appropriate and successful.
  32. TC_Extension, ///< The cast method is appropriate and accepted as a
  33. ///< language extension.
  34. TC_Failed ///< The cast method is appropriate, but failed. A
  35. ///< diagnostic has been emitted.
  36. };
  37. static bool isValidCast(TryCastResult TCR) {
  38. return TCR == TC_Success || TCR == TC_Extension;
  39. }
  40. enum CastType {
  41. CT_Const, ///< const_cast
  42. CT_Static, ///< static_cast
  43. CT_Reinterpret, ///< reinterpret_cast
  44. CT_Dynamic, ///< dynamic_cast
  45. CT_CStyle, ///< (Type)expr
  46. CT_Functional ///< Type(expr)
  47. };
  48. namespace {
  49. struct CastOperation {
  50. CastOperation(Sema &S, QualType destType, ExprResult src)
  51. : Self(S), SrcExpr(src), DestType(destType),
  52. ResultType(destType.getNonLValueExprType(S.Context)),
  53. ValueKind(Expr::getValueKindForType(destType)),
  54. Kind(CK_Dependent), IsARCUnbridgedCast(false) {
  55. if (const BuiltinType *placeholder =
  56. src.get()->getType()->getAsPlaceholderType()) {
  57. PlaceholderKind = placeholder->getKind();
  58. } else {
  59. PlaceholderKind = (BuiltinType::Kind) 0;
  60. }
  61. }
  62. Sema &Self;
  63. ExprResult SrcExpr;
  64. QualType DestType;
  65. QualType ResultType;
  66. ExprValueKind ValueKind;
  67. CastKind Kind;
  68. BuiltinType::Kind PlaceholderKind;
  69. CXXCastPath BasePath;
  70. bool IsARCUnbridgedCast;
  71. SourceRange OpRange;
  72. SourceRange DestRange;
  73. // Top-level semantics-checking routines.
  74. void CheckConstCast();
  75. void CheckReinterpretCast();
  76. void CheckStaticCast();
  77. void CheckDynamicCast();
  78. void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
  79. void CheckCStyleCast();
  80. void updatePartOfExplicitCastFlags(CastExpr *CE) {
  81. // Walk down from the CE to the OrigSrcExpr, and mark all immediate
  82. // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
  83. // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
  84. while ((CE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr())))
  85. CE->setIsPartOfExplicitCast(true);
  86. }
  87. /// Complete an apparently-successful cast operation that yields
  88. /// the given expression.
  89. ExprResult complete(CastExpr *castExpr) {
  90. // If this is an unbridged cast, wrap the result in an implicit
  91. // cast that yields the unbridged-cast placeholder type.
  92. if (IsARCUnbridgedCast) {
  93. castExpr = ImplicitCastExpr::Create(Self.Context,
  94. Self.Context.ARCUnbridgedCastTy,
  95. CK_Dependent, castExpr, nullptr,
  96. castExpr->getValueKind());
  97. }
  98. updatePartOfExplicitCastFlags(castExpr);
  99. return castExpr;
  100. }
  101. // Internal convenience methods.
  102. /// Try to handle the given placeholder expression kind. Return
  103. /// true if the source expression has the appropriate placeholder
  104. /// kind. A placeholder can only be claimed once.
  105. bool claimPlaceholder(BuiltinType::Kind K) {
  106. if (PlaceholderKind != K) return false;
  107. PlaceholderKind = (BuiltinType::Kind) 0;
  108. return true;
  109. }
  110. bool isPlaceholder() const {
  111. return PlaceholderKind != 0;
  112. }
  113. bool isPlaceholder(BuiltinType::Kind K) const {
  114. return PlaceholderKind == K;
  115. }
  116. void checkCastAlign() {
  117. Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
  118. }
  119. void checkObjCConversion(Sema::CheckedConversionKind CCK) {
  120. assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
  121. Expr *src = SrcExpr.get();
  122. if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
  123. Sema::ACR_unbridged)
  124. IsARCUnbridgedCast = true;
  125. SrcExpr = src;
  126. }
  127. /// Check for and handle non-overload placeholder expressions.
  128. void checkNonOverloadPlaceholders() {
  129. if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
  130. return;
  131. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  132. if (SrcExpr.isInvalid())
  133. return;
  134. PlaceholderKind = (BuiltinType::Kind) 0;
  135. }
  136. };
  137. }
  138. static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
  139. QualType DestType);
  140. // The Try functions attempt a specific way of casting. If they succeed, they
  141. // return TC_Success. If their way of casting is not appropriate for the given
  142. // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
  143. // to emit if no other way succeeds. If their way of casting is appropriate but
  144. // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
  145. // they emit a specialized diagnostic.
  146. // All diagnostics returned by these functions must expect the same three
  147. // arguments:
  148. // %0: Cast Type (a value from the CastType enumeration)
  149. // %1: Source Type
  150. // %2: Destination Type
  151. static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
  152. QualType DestType, bool CStyle,
  153. CastKind &Kind,
  154. CXXCastPath &BasePath,
  155. unsigned &msg);
  156. static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
  157. QualType DestType, bool CStyle,
  158. SourceRange OpRange,
  159. unsigned &msg,
  160. CastKind &Kind,
  161. CXXCastPath &BasePath);
  162. static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
  163. QualType DestType, bool CStyle,
  164. SourceRange OpRange,
  165. unsigned &msg,
  166. CastKind &Kind,
  167. CXXCastPath &BasePath);
  168. static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
  169. CanQualType DestType, bool CStyle,
  170. SourceRange OpRange,
  171. QualType OrigSrcType,
  172. QualType OrigDestType, unsigned &msg,
  173. CastKind &Kind,
  174. CXXCastPath &BasePath);
  175. static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
  176. QualType SrcType,
  177. QualType DestType,bool CStyle,
  178. SourceRange OpRange,
  179. unsigned &msg,
  180. CastKind &Kind,
  181. CXXCastPath &BasePath);
  182. static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
  183. QualType DestType,
  184. Sema::CheckedConversionKind CCK,
  185. SourceRange OpRange,
  186. unsigned &msg, CastKind &Kind,
  187. bool ListInitialization);
  188. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
  189. QualType DestType,
  190. Sema::CheckedConversionKind CCK,
  191. SourceRange OpRange,
  192. unsigned &msg, CastKind &Kind,
  193. CXXCastPath &BasePath,
  194. bool ListInitialization);
  195. static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
  196. QualType DestType, bool CStyle,
  197. unsigned &msg);
  198. static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
  199. QualType DestType, bool CStyle,
  200. SourceRange OpRange,
  201. unsigned &msg,
  202. CastKind &Kind);
  203. /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
  204. ExprResult
  205. Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
  206. SourceLocation LAngleBracketLoc, Declarator &D,
  207. SourceLocation RAngleBracketLoc,
  208. SourceLocation LParenLoc, Expr *E,
  209. SourceLocation RParenLoc) {
  210. assert(!D.isInvalidType());
  211. TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
  212. if (D.isInvalidType())
  213. return ExprError();
  214. if (getLangOpts().CPlusPlus) {
  215. // Check that there are no default arguments (C++ only).
  216. CheckExtraCXXDefaultArguments(D);
  217. }
  218. return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
  219. SourceRange(LAngleBracketLoc, RAngleBracketLoc),
  220. SourceRange(LParenLoc, RParenLoc));
  221. }
  222. ExprResult
  223. Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
  224. TypeSourceInfo *DestTInfo, Expr *E,
  225. SourceRange AngleBrackets, SourceRange Parens) {
  226. ExprResult Ex = E;
  227. QualType DestType = DestTInfo->getType();
  228. // If the type is dependent, we won't do the semantic analysis now.
  229. bool TypeDependent =
  230. DestType->isDependentType() || Ex.get()->isTypeDependent();
  231. CastOperation Op(*this, DestType, E);
  232. Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
  233. Op.DestRange = AngleBrackets;
  234. switch (Kind) {
  235. default: llvm_unreachable("Unknown C++ cast!");
  236. case tok::kw_const_cast:
  237. if (!TypeDependent) {
  238. Op.CheckConstCast();
  239. if (Op.SrcExpr.isInvalid())
  240. return ExprError();
  241. DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
  242. }
  243. return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
  244. Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
  245. OpLoc, Parens.getEnd(),
  246. AngleBrackets));
  247. case tok::kw_dynamic_cast: {
  248. // OpenCL C++ 1.0 s2.9: dynamic_cast is not supported.
  249. if (getLangOpts().OpenCLCPlusPlus) {
  250. return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
  251. << "dynamic_cast");
  252. }
  253. if (!TypeDependent) {
  254. Op.CheckDynamicCast();
  255. if (Op.SrcExpr.isInvalid())
  256. return ExprError();
  257. }
  258. return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
  259. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  260. &Op.BasePath, DestTInfo,
  261. OpLoc, Parens.getEnd(),
  262. AngleBrackets));
  263. }
  264. case tok::kw_reinterpret_cast: {
  265. if (!TypeDependent) {
  266. Op.CheckReinterpretCast();
  267. if (Op.SrcExpr.isInvalid())
  268. return ExprError();
  269. DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
  270. }
  271. return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
  272. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  273. nullptr, DestTInfo, OpLoc,
  274. Parens.getEnd(),
  275. AngleBrackets));
  276. }
  277. case tok::kw_static_cast: {
  278. if (!TypeDependent) {
  279. Op.CheckStaticCast();
  280. if (Op.SrcExpr.isInvalid())
  281. return ExprError();
  282. DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
  283. }
  284. return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
  285. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  286. &Op.BasePath, DestTInfo,
  287. OpLoc, Parens.getEnd(),
  288. AngleBrackets));
  289. }
  290. }
  291. }
  292. /// Try to diagnose a failed overloaded cast. Returns true if
  293. /// diagnostics were emitted.
  294. static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
  295. SourceRange range, Expr *src,
  296. QualType destType,
  297. bool listInitialization) {
  298. switch (CT) {
  299. // These cast kinds don't consider user-defined conversions.
  300. case CT_Const:
  301. case CT_Reinterpret:
  302. case CT_Dynamic:
  303. return false;
  304. // These do.
  305. case CT_Static:
  306. case CT_CStyle:
  307. case CT_Functional:
  308. break;
  309. }
  310. QualType srcType = src->getType();
  311. if (!destType->isRecordType() && !srcType->isRecordType())
  312. return false;
  313. InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
  314. InitializationKind initKind
  315. = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
  316. range, listInitialization)
  317. : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
  318. listInitialization)
  319. : InitializationKind::CreateCast(/*type range?*/ range);
  320. InitializationSequence sequence(S, entity, initKind, src);
  321. assert(sequence.Failed() && "initialization succeeded on second try?");
  322. switch (sequence.getFailureKind()) {
  323. default: return false;
  324. case InitializationSequence::FK_ConstructorOverloadFailed:
  325. case InitializationSequence::FK_UserConversionOverloadFailed:
  326. break;
  327. }
  328. OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
  329. unsigned msg = 0;
  330. OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
  331. switch (sequence.getFailedOverloadResult()) {
  332. case OR_Success: llvm_unreachable("successful failed overload");
  333. case OR_No_Viable_Function:
  334. if (candidates.empty())
  335. msg = diag::err_ovl_no_conversion_in_cast;
  336. else
  337. msg = diag::err_ovl_no_viable_conversion_in_cast;
  338. howManyCandidates = OCD_AllCandidates;
  339. break;
  340. case OR_Ambiguous:
  341. msg = diag::err_ovl_ambiguous_conversion_in_cast;
  342. howManyCandidates = OCD_ViableCandidates;
  343. break;
  344. case OR_Deleted:
  345. msg = diag::err_ovl_deleted_conversion_in_cast;
  346. howManyCandidates = OCD_ViableCandidates;
  347. break;
  348. }
  349. S.Diag(range.getBegin(), msg)
  350. << CT << srcType << destType
  351. << range << src->getSourceRange();
  352. candidates.NoteCandidates(S, howManyCandidates, src);
  353. return true;
  354. }
  355. /// Diagnose a failed cast.
  356. static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
  357. SourceRange opRange, Expr *src, QualType destType,
  358. bool listInitialization) {
  359. if (msg == diag::err_bad_cxx_cast_generic &&
  360. tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
  361. listInitialization))
  362. return;
  363. S.Diag(opRange.getBegin(), msg) << castType
  364. << src->getType() << destType << opRange << src->getSourceRange();
  365. // Detect if both types are (ptr to) class, and note any incompleteness.
  366. int DifferentPtrness = 0;
  367. QualType From = destType;
  368. if (auto Ptr = From->getAs<PointerType>()) {
  369. From = Ptr->getPointeeType();
  370. DifferentPtrness++;
  371. }
  372. QualType To = src->getType();
  373. if (auto Ptr = To->getAs<PointerType>()) {
  374. To = Ptr->getPointeeType();
  375. DifferentPtrness--;
  376. }
  377. if (!DifferentPtrness) {
  378. auto RecFrom = From->getAs<RecordType>();
  379. auto RecTo = To->getAs<RecordType>();
  380. if (RecFrom && RecTo) {
  381. auto DeclFrom = RecFrom->getAsCXXRecordDecl();
  382. if (!DeclFrom->isCompleteDefinition())
  383. S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
  384. << DeclFrom->getDeclName();
  385. auto DeclTo = RecTo->getAsCXXRecordDecl();
  386. if (!DeclTo->isCompleteDefinition())
  387. S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
  388. << DeclTo->getDeclName();
  389. }
  390. }
  391. }
  392. namespace {
  393. /// The kind of unwrapping we did when determining whether a conversion casts
  394. /// away constness.
  395. enum CastAwayConstnessKind {
  396. /// The conversion does not cast away constness.
  397. CACK_None = 0,
  398. /// We unwrapped similar types.
  399. CACK_Similar = 1,
  400. /// We unwrapped dissimilar types with similar representations (eg, a pointer
  401. /// versus an Objective-C object pointer).
  402. CACK_SimilarKind = 2,
  403. /// We unwrapped representationally-unrelated types, such as a pointer versus
  404. /// a pointer-to-member.
  405. CACK_Incoherent = 3,
  406. };
  407. }
  408. /// Unwrap one level of types for CastsAwayConstness.
  409. ///
  410. /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
  411. /// both types, provided that they're both pointer-like or array-like. Unlike
  412. /// the Sema function, doesn't care if the unwrapped pieces are related.
  413. ///
  414. /// This function may remove additional levels as necessary for correctness:
  415. /// the resulting T1 is unwrapped sufficiently that it is never an array type,
  416. /// so that its qualifiers can be directly compared to those of T2 (which will
  417. /// have the combined set of qualifiers from all indermediate levels of T2),
  418. /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
  419. /// with those from T2.
  420. static CastAwayConstnessKind
  421. unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
  422. enum { None, Ptr, MemPtr, BlockPtr, Array };
  423. auto Classify = [](QualType T) {
  424. if (T->isAnyPointerType()) return Ptr;
  425. if (T->isMemberPointerType()) return MemPtr;
  426. if (T->isBlockPointerType()) return BlockPtr;
  427. // We somewhat-arbitrarily don't look through VLA types here. This is at
  428. // least consistent with the behavior of UnwrapSimilarTypes.
  429. if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
  430. return None;
  431. };
  432. auto Unwrap = [&](QualType T) {
  433. if (auto *AT = Context.getAsArrayType(T))
  434. return AT->getElementType();
  435. return T->getPointeeType();
  436. };
  437. CastAwayConstnessKind Kind;
  438. if (T2->isReferenceType()) {
  439. // Special case: if the destination type is a reference type, unwrap it as
  440. // the first level. (The source will have been an lvalue expression in this
  441. // case, so there is no corresponding "reference to" in T1 to remove.) This
  442. // simulates removing a "pointer to" from both sides.
  443. T2 = T2->getPointeeType();
  444. Kind = CastAwayConstnessKind::CACK_Similar;
  445. } else if (Context.UnwrapSimilarTypes(T1, T2)) {
  446. Kind = CastAwayConstnessKind::CACK_Similar;
  447. } else {
  448. // Try unwrapping mismatching levels.
  449. int T1Class = Classify(T1);
  450. if (T1Class == None)
  451. return CastAwayConstnessKind::CACK_None;
  452. int T2Class = Classify(T2);
  453. if (T2Class == None)
  454. return CastAwayConstnessKind::CACK_None;
  455. T1 = Unwrap(T1);
  456. T2 = Unwrap(T2);
  457. Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
  458. : CastAwayConstnessKind::CACK_Incoherent;
  459. }
  460. // We've unwrapped at least one level. If the resulting T1 is a (possibly
  461. // multidimensional) array type, any qualifier on any matching layer of
  462. // T2 is considered to correspond to T1. Decompose down to the element
  463. // type of T1 so that we can compare properly.
  464. while (true) {
  465. Context.UnwrapSimilarArrayTypes(T1, T2);
  466. if (Classify(T1) != Array)
  467. break;
  468. auto T2Class = Classify(T2);
  469. if (T2Class == None)
  470. break;
  471. if (T2Class != Array)
  472. Kind = CastAwayConstnessKind::CACK_Incoherent;
  473. else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
  474. Kind = CastAwayConstnessKind::CACK_SimilarKind;
  475. T1 = Unwrap(T1);
  476. T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
  477. }
  478. return Kind;
  479. }
  480. /// Check if the pointer conversion from SrcType to DestType casts away
  481. /// constness as defined in C++ [expr.const.cast]. This is used by the cast
  482. /// checkers. Both arguments must denote pointer (possibly to member) types.
  483. ///
  484. /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
  485. /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
  486. static CastAwayConstnessKind
  487. CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
  488. bool CheckCVR, bool CheckObjCLifetime,
  489. QualType *TheOffendingSrcType = nullptr,
  490. QualType *TheOffendingDestType = nullptr,
  491. Qualifiers *CastAwayQualifiers = nullptr) {
  492. // If the only checking we care about is for Objective-C lifetime qualifiers,
  493. // and we're not in ObjC mode, there's nothing to check.
  494. if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC1)
  495. return CastAwayConstnessKind::CACK_None;
  496. if (!DestType->isReferenceType()) {
  497. assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
  498. SrcType->isBlockPointerType()) &&
  499. "Source type is not pointer or pointer to member.");
  500. assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
  501. DestType->isBlockPointerType()) &&
  502. "Destination type is not pointer or pointer to member.");
  503. }
  504. QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
  505. UnwrappedDestType = Self.Context.getCanonicalType(DestType);
  506. // Find the qualifiers. We only care about cvr-qualifiers for the
  507. // purpose of this check, because other qualifiers (address spaces,
  508. // Objective-C GC, etc.) are part of the type's identity.
  509. QualType PrevUnwrappedSrcType = UnwrappedSrcType;
  510. QualType PrevUnwrappedDestType = UnwrappedDestType;
  511. auto WorstKind = CastAwayConstnessKind::CACK_Similar;
  512. bool AllConstSoFar = true;
  513. while (auto Kind = unwrapCastAwayConstnessLevel(
  514. Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
  515. // Track the worst kind of unwrap we needed to do before we found a
  516. // problem.
  517. if (Kind > WorstKind)
  518. WorstKind = Kind;
  519. // Determine the relevant qualifiers at this level.
  520. Qualifiers SrcQuals, DestQuals;
  521. Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
  522. Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
  523. // We do not meaningfully track object const-ness of Objective-C object
  524. // types. Remove const from the source type if either the source or
  525. // the destination is an Objective-C object type.
  526. if (UnwrappedSrcType->isObjCObjectType() ||
  527. UnwrappedDestType->isObjCObjectType())
  528. SrcQuals.removeConst();
  529. if (CheckCVR) {
  530. Qualifiers SrcCvrQuals =
  531. Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
  532. Qualifiers DestCvrQuals =
  533. Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
  534. if (SrcCvrQuals != DestCvrQuals) {
  535. if (CastAwayQualifiers)
  536. *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
  537. // If we removed a cvr-qualifier, this is casting away 'constness'.
  538. if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
  539. if (TheOffendingSrcType)
  540. *TheOffendingSrcType = PrevUnwrappedSrcType;
  541. if (TheOffendingDestType)
  542. *TheOffendingDestType = PrevUnwrappedDestType;
  543. return WorstKind;
  544. }
  545. // If any prior level was not 'const', this is also casting away
  546. // 'constness'. We noted the outermost type missing a 'const' already.
  547. if (!AllConstSoFar)
  548. return WorstKind;
  549. }
  550. }
  551. if (CheckObjCLifetime &&
  552. !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
  553. return WorstKind;
  554. // If we found our first non-const-qualified type, this may be the place
  555. // where things start to go wrong.
  556. if (AllConstSoFar && !DestQuals.hasConst()) {
  557. AllConstSoFar = false;
  558. if (TheOffendingSrcType)
  559. *TheOffendingSrcType = PrevUnwrappedSrcType;
  560. if (TheOffendingDestType)
  561. *TheOffendingDestType = PrevUnwrappedDestType;
  562. }
  563. PrevUnwrappedSrcType = UnwrappedSrcType;
  564. PrevUnwrappedDestType = UnwrappedDestType;
  565. }
  566. return CastAwayConstnessKind::CACK_None;
  567. }
  568. static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
  569. unsigned &DiagID) {
  570. switch (CACK) {
  571. case CastAwayConstnessKind::CACK_None:
  572. llvm_unreachable("did not cast away constness");
  573. case CastAwayConstnessKind::CACK_Similar:
  574. // FIXME: Accept these as an extension too?
  575. case CastAwayConstnessKind::CACK_SimilarKind:
  576. DiagID = diag::err_bad_cxx_cast_qualifiers_away;
  577. return TC_Failed;
  578. case CastAwayConstnessKind::CACK_Incoherent:
  579. DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
  580. return TC_Extension;
  581. }
  582. llvm_unreachable("unexpected cast away constness kind");
  583. }
  584. /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
  585. /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
  586. /// checked downcasts in class hierarchies.
  587. void CastOperation::CheckDynamicCast() {
  588. if (ValueKind == VK_RValue)
  589. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  590. else if (isPlaceholder())
  591. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  592. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  593. return;
  594. QualType OrigSrcType = SrcExpr.get()->getType();
  595. QualType DestType = Self.Context.getCanonicalType(this->DestType);
  596. // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
  597. // or "pointer to cv void".
  598. QualType DestPointee;
  599. const PointerType *DestPointer = DestType->getAs<PointerType>();
  600. const ReferenceType *DestReference = nullptr;
  601. if (DestPointer) {
  602. DestPointee = DestPointer->getPointeeType();
  603. } else if ((DestReference = DestType->getAs<ReferenceType>())) {
  604. DestPointee = DestReference->getPointeeType();
  605. } else {
  606. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
  607. << this->DestType << DestRange;
  608. SrcExpr = ExprError();
  609. return;
  610. }
  611. const RecordType *DestRecord = DestPointee->getAs<RecordType>();
  612. if (DestPointee->isVoidType()) {
  613. assert(DestPointer && "Reference to void is not possible");
  614. } else if (DestRecord) {
  615. if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
  616. diag::err_bad_dynamic_cast_incomplete,
  617. DestRange)) {
  618. SrcExpr = ExprError();
  619. return;
  620. }
  621. } else {
  622. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
  623. << DestPointee.getUnqualifiedType() << DestRange;
  624. SrcExpr = ExprError();
  625. return;
  626. }
  627. // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
  628. // complete class type, [...]. If T is an lvalue reference type, v shall be
  629. // an lvalue of a complete class type, [...]. If T is an rvalue reference
  630. // type, v shall be an expression having a complete class type, [...]
  631. QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
  632. QualType SrcPointee;
  633. if (DestPointer) {
  634. if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
  635. SrcPointee = SrcPointer->getPointeeType();
  636. } else {
  637. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
  638. << OrigSrcType << SrcExpr.get()->getSourceRange();
  639. SrcExpr = ExprError();
  640. return;
  641. }
  642. } else if (DestReference->isLValueReferenceType()) {
  643. if (!SrcExpr.get()->isLValue()) {
  644. Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
  645. << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
  646. }
  647. SrcPointee = SrcType;
  648. } else {
  649. // If we're dynamic_casting from a prvalue to an rvalue reference, we need
  650. // to materialize the prvalue before we bind the reference to it.
  651. if (SrcExpr.get()->isRValue())
  652. SrcExpr = Self.CreateMaterializeTemporaryExpr(
  653. SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
  654. SrcPointee = SrcType;
  655. }
  656. const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
  657. if (SrcRecord) {
  658. if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
  659. diag::err_bad_dynamic_cast_incomplete,
  660. SrcExpr.get())) {
  661. SrcExpr = ExprError();
  662. return;
  663. }
  664. } else {
  665. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
  666. << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
  667. SrcExpr = ExprError();
  668. return;
  669. }
  670. assert((DestPointer || DestReference) &&
  671. "Bad destination non-ptr/ref slipped through.");
  672. assert((DestRecord || DestPointee->isVoidType()) &&
  673. "Bad destination pointee slipped through.");
  674. assert(SrcRecord && "Bad source pointee slipped through.");
  675. // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
  676. if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
  677. Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
  678. << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
  679. SrcExpr = ExprError();
  680. return;
  681. }
  682. // C++ 5.2.7p3: If the type of v is the same as the required result type,
  683. // [except for cv].
  684. if (DestRecord == SrcRecord) {
  685. Kind = CK_NoOp;
  686. return;
  687. }
  688. // C++ 5.2.7p5
  689. // Upcasts are resolved statically.
  690. if (DestRecord &&
  691. Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
  692. if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
  693. OpRange.getBegin(), OpRange,
  694. &BasePath)) {
  695. SrcExpr = ExprError();
  696. return;
  697. }
  698. Kind = CK_DerivedToBase;
  699. return;
  700. }
  701. // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
  702. const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
  703. assert(SrcDecl && "Definition missing");
  704. if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
  705. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
  706. << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
  707. SrcExpr = ExprError();
  708. }
  709. // dynamic_cast is not available with -fno-rtti.
  710. // As an exception, dynamic_cast to void* is available because it doesn't
  711. // use RTTI.
  712. if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
  713. Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
  714. SrcExpr = ExprError();
  715. return;
  716. }
  717. // Done. Everything else is run-time checks.
  718. Kind = CK_Dynamic;
  719. }
  720. /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
  721. /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
  722. /// like this:
  723. /// const char *str = "literal";
  724. /// legacy_function(const_cast\<char*\>(str));
  725. void CastOperation::CheckConstCast() {
  726. if (ValueKind == VK_RValue)
  727. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  728. else if (isPlaceholder())
  729. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  730. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  731. return;
  732. unsigned msg = diag::err_bad_cxx_cast_generic;
  733. auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
  734. if (TCR != TC_Success && msg != 0) {
  735. Self.Diag(OpRange.getBegin(), msg) << CT_Const
  736. << SrcExpr.get()->getType() << DestType << OpRange;
  737. }
  738. if (!isValidCast(TCR))
  739. SrcExpr = ExprError();
  740. }
  741. /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
  742. /// or downcast between respective pointers or references.
  743. static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
  744. QualType DestType,
  745. SourceRange OpRange) {
  746. QualType SrcType = SrcExpr->getType();
  747. // When casting from pointer or reference, get pointee type; use original
  748. // type otherwise.
  749. const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
  750. const CXXRecordDecl *SrcRD =
  751. SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
  752. // Examining subobjects for records is only possible if the complete and
  753. // valid definition is available. Also, template instantiation is not
  754. // allowed here.
  755. if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
  756. return;
  757. const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
  758. if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
  759. return;
  760. enum {
  761. ReinterpretUpcast,
  762. ReinterpretDowncast
  763. } ReinterpretKind;
  764. CXXBasePaths BasePaths;
  765. if (SrcRD->isDerivedFrom(DestRD, BasePaths))
  766. ReinterpretKind = ReinterpretUpcast;
  767. else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
  768. ReinterpretKind = ReinterpretDowncast;
  769. else
  770. return;
  771. bool VirtualBase = true;
  772. bool NonZeroOffset = false;
  773. for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
  774. E = BasePaths.end();
  775. I != E; ++I) {
  776. const CXXBasePath &Path = *I;
  777. CharUnits Offset = CharUnits::Zero();
  778. bool IsVirtual = false;
  779. for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
  780. IElem != EElem; ++IElem) {
  781. IsVirtual = IElem->Base->isVirtual();
  782. if (IsVirtual)
  783. break;
  784. const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
  785. assert(BaseRD && "Base type should be a valid unqualified class type");
  786. // Don't check if any base has invalid declaration or has no definition
  787. // since it has no layout info.
  788. const CXXRecordDecl *Class = IElem->Class,
  789. *ClassDefinition = Class->getDefinition();
  790. if (Class->isInvalidDecl() || !ClassDefinition ||
  791. !ClassDefinition->isCompleteDefinition())
  792. return;
  793. const ASTRecordLayout &DerivedLayout =
  794. Self.Context.getASTRecordLayout(Class);
  795. Offset += DerivedLayout.getBaseClassOffset(BaseRD);
  796. }
  797. if (!IsVirtual) {
  798. // Don't warn if any path is a non-virtually derived base at offset zero.
  799. if (Offset.isZero())
  800. return;
  801. // Offset makes sense only for non-virtual bases.
  802. else
  803. NonZeroOffset = true;
  804. }
  805. VirtualBase = VirtualBase && IsVirtual;
  806. }
  807. (void) NonZeroOffset; // Silence set but not used warning.
  808. assert((VirtualBase || NonZeroOffset) &&
  809. "Should have returned if has non-virtual base with zero offset");
  810. QualType BaseType =
  811. ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
  812. QualType DerivedType =
  813. ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
  814. SourceLocation BeginLoc = OpRange.getBegin();
  815. Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
  816. << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
  817. << OpRange;
  818. Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
  819. << int(ReinterpretKind)
  820. << FixItHint::CreateReplacement(BeginLoc, "static_cast");
  821. }
  822. /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
  823. /// valid.
  824. /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
  825. /// like this:
  826. /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
  827. void CastOperation::CheckReinterpretCast() {
  828. if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
  829. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  830. else
  831. checkNonOverloadPlaceholders();
  832. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  833. return;
  834. unsigned msg = diag::err_bad_cxx_cast_generic;
  835. TryCastResult tcr =
  836. TryReinterpretCast(Self, SrcExpr, DestType,
  837. /*CStyle*/false, OpRange, msg, Kind);
  838. if (tcr != TC_Success && msg != 0) {
  839. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  840. return;
  841. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  842. //FIXME: &f<int>; is overloaded and resolvable
  843. Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
  844. << OverloadExpr::find(SrcExpr.get()).Expression->getName()
  845. << DestType << OpRange;
  846. Self.NoteAllOverloadCandidates(SrcExpr.get());
  847. } else {
  848. diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
  849. DestType, /*listInitialization=*/false);
  850. }
  851. }
  852. if (isValidCast(tcr)) {
  853. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
  854. checkObjCConversion(Sema::CCK_OtherCast);
  855. DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
  856. } else {
  857. SrcExpr = ExprError();
  858. }
  859. }
  860. /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
  861. /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
  862. /// implicit conversions explicit and getting rid of data loss warnings.
  863. void CastOperation::CheckStaticCast() {
  864. if (isPlaceholder()) {
  865. checkNonOverloadPlaceholders();
  866. if (SrcExpr.isInvalid())
  867. return;
  868. }
  869. // This test is outside everything else because it's the only case where
  870. // a non-lvalue-reference target type does not lead to decay.
  871. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  872. if (DestType->isVoidType()) {
  873. Kind = CK_ToVoid;
  874. if (claimPlaceholder(BuiltinType::Overload)) {
  875. Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
  876. false, // Decay Function to ptr
  877. true, // Complain
  878. OpRange, DestType, diag::err_bad_static_cast_overload);
  879. if (SrcExpr.isInvalid())
  880. return;
  881. }
  882. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  883. return;
  884. }
  885. if (ValueKind == VK_RValue && !DestType->isRecordType() &&
  886. !isPlaceholder(BuiltinType::Overload)) {
  887. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  888. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  889. return;
  890. }
  891. unsigned msg = diag::err_bad_cxx_cast_generic;
  892. TryCastResult tcr
  893. = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
  894. Kind, BasePath, /*ListInitialization=*/false);
  895. if (tcr != TC_Success && msg != 0) {
  896. if (SrcExpr.isInvalid())
  897. return;
  898. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  899. OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
  900. Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
  901. << oe->getName() << DestType << OpRange
  902. << oe->getQualifierLoc().getSourceRange();
  903. Self.NoteAllOverloadCandidates(SrcExpr.get());
  904. } else {
  905. diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
  906. /*listInitialization=*/false);
  907. }
  908. }
  909. if (isValidCast(tcr)) {
  910. if (Kind == CK_BitCast)
  911. checkCastAlign();
  912. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
  913. checkObjCConversion(Sema::CCK_OtherCast);
  914. } else {
  915. SrcExpr = ExprError();
  916. }
  917. }
  918. /// TryStaticCast - Check if a static cast can be performed, and do so if
  919. /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
  920. /// and casting away constness.
  921. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
  922. QualType DestType,
  923. Sema::CheckedConversionKind CCK,
  924. SourceRange OpRange, unsigned &msg,
  925. CastKind &Kind, CXXCastPath &BasePath,
  926. bool ListInitialization) {
  927. // Determine whether we have the semantics of a C-style cast.
  928. bool CStyle
  929. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  930. // The order the tests is not entirely arbitrary. There is one conversion
  931. // that can be handled in two different ways. Given:
  932. // struct A {};
  933. // struct B : public A {
  934. // B(); B(const A&);
  935. // };
  936. // const A &a = B();
  937. // the cast static_cast<const B&>(a) could be seen as either a static
  938. // reference downcast, or an explicit invocation of the user-defined
  939. // conversion using B's conversion constructor.
  940. // DR 427 specifies that the downcast is to be applied here.
  941. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  942. // Done outside this function.
  943. TryCastResult tcr;
  944. // C++ 5.2.9p5, reference downcast.
  945. // See the function for details.
  946. // DR 427 specifies that this is to be applied before paragraph 2.
  947. tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
  948. OpRange, msg, Kind, BasePath);
  949. if (tcr != TC_NotApplicable)
  950. return tcr;
  951. // C++11 [expr.static.cast]p3:
  952. // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
  953. // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
  954. tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
  955. BasePath, msg);
  956. if (tcr != TC_NotApplicable)
  957. return tcr;
  958. // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
  959. // [...] if the declaration "T t(e);" is well-formed, [...].
  960. tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
  961. Kind, ListInitialization);
  962. if (SrcExpr.isInvalid())
  963. return TC_Failed;
  964. if (tcr != TC_NotApplicable)
  965. return tcr;
  966. // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
  967. // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
  968. // conversions, subject to further restrictions.
  969. // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
  970. // of qualification conversions impossible.
  971. // In the CStyle case, the earlier attempt to const_cast should have taken
  972. // care of reverse qualification conversions.
  973. QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
  974. // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
  975. // converted to an integral type. [...] A value of a scoped enumeration type
  976. // can also be explicitly converted to a floating-point type [...].
  977. if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
  978. if (Enum->getDecl()->isScoped()) {
  979. if (DestType->isBooleanType()) {
  980. Kind = CK_IntegralToBoolean;
  981. return TC_Success;
  982. } else if (DestType->isIntegralType(Self.Context)) {
  983. Kind = CK_IntegralCast;
  984. return TC_Success;
  985. } else if (DestType->isRealFloatingType()) {
  986. Kind = CK_IntegralToFloating;
  987. return TC_Success;
  988. }
  989. }
  990. }
  991. // Reverse integral promotion/conversion. All such conversions are themselves
  992. // again integral promotions or conversions and are thus already handled by
  993. // p2 (TryDirectInitialization above).
  994. // (Note: any data loss warnings should be suppressed.)
  995. // The exception is the reverse of enum->integer, i.e. integer->enum (and
  996. // enum->enum). See also C++ 5.2.9p7.
  997. // The same goes for reverse floating point promotion/conversion and
  998. // floating-integral conversions. Again, only floating->enum is relevant.
  999. if (DestType->isEnumeralType()) {
  1000. if (SrcType->isIntegralOrEnumerationType()) {
  1001. Kind = CK_IntegralCast;
  1002. return TC_Success;
  1003. } else if (SrcType->isRealFloatingType()) {
  1004. Kind = CK_FloatingToIntegral;
  1005. return TC_Success;
  1006. }
  1007. }
  1008. // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
  1009. // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
  1010. tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
  1011. Kind, BasePath);
  1012. if (tcr != TC_NotApplicable)
  1013. return tcr;
  1014. // Reverse member pointer conversion. C++ 4.11 specifies member pointer
  1015. // conversion. C++ 5.2.9p9 has additional information.
  1016. // DR54's access restrictions apply here also.
  1017. tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
  1018. OpRange, msg, Kind, BasePath);
  1019. if (tcr != TC_NotApplicable)
  1020. return tcr;
  1021. // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
  1022. // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
  1023. // just the usual constness stuff.
  1024. if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
  1025. QualType SrcPointee = SrcPointer->getPointeeType();
  1026. if (SrcPointee->isVoidType()) {
  1027. if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
  1028. QualType DestPointee = DestPointer->getPointeeType();
  1029. if (DestPointee->isIncompleteOrObjectType()) {
  1030. // This is definitely the intended conversion, but it might fail due
  1031. // to a qualifier violation. Note that we permit Objective-C lifetime
  1032. // and GC qualifier mismatches here.
  1033. if (!CStyle) {
  1034. Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
  1035. Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
  1036. DestPointeeQuals.removeObjCGCAttr();
  1037. DestPointeeQuals.removeObjCLifetime();
  1038. SrcPointeeQuals.removeObjCGCAttr();
  1039. SrcPointeeQuals.removeObjCLifetime();
  1040. if (DestPointeeQuals != SrcPointeeQuals &&
  1041. !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
  1042. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1043. return TC_Failed;
  1044. }
  1045. }
  1046. Kind = CK_BitCast;
  1047. return TC_Success;
  1048. }
  1049. // Microsoft permits static_cast from 'pointer-to-void' to
  1050. // 'pointer-to-function'.
  1051. if (!CStyle && Self.getLangOpts().MSVCCompat &&
  1052. DestPointee->isFunctionType()) {
  1053. Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
  1054. Kind = CK_BitCast;
  1055. return TC_Success;
  1056. }
  1057. }
  1058. else if (DestType->isObjCObjectPointerType()) {
  1059. // allow both c-style cast and static_cast of objective-c pointers as
  1060. // they are pervasive.
  1061. Kind = CK_CPointerToObjCPointerCast;
  1062. return TC_Success;
  1063. }
  1064. else if (CStyle && DestType->isBlockPointerType()) {
  1065. // allow c-style cast of void * to block pointers.
  1066. Kind = CK_AnyPointerToBlockPointerCast;
  1067. return TC_Success;
  1068. }
  1069. }
  1070. }
  1071. // Allow arbitrary objective-c pointer conversion with static casts.
  1072. if (SrcType->isObjCObjectPointerType() &&
  1073. DestType->isObjCObjectPointerType()) {
  1074. Kind = CK_BitCast;
  1075. return TC_Success;
  1076. }
  1077. // Allow ns-pointer to cf-pointer conversion in either direction
  1078. // with static casts.
  1079. if (!CStyle &&
  1080. Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
  1081. return TC_Success;
  1082. // See if it looks like the user is trying to convert between
  1083. // related record types, and select a better diagnostic if so.
  1084. if (auto SrcPointer = SrcType->getAs<PointerType>())
  1085. if (auto DestPointer = DestType->getAs<PointerType>())
  1086. if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
  1087. DestPointer->getPointeeType()->getAs<RecordType>())
  1088. msg = diag::err_bad_cxx_cast_unrelated_class;
  1089. // We tried everything. Everything! Nothing works! :-(
  1090. return TC_NotApplicable;
  1091. }
  1092. /// Tests whether a conversion according to N2844 is valid.
  1093. TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
  1094. QualType DestType, bool CStyle,
  1095. CastKind &Kind, CXXCastPath &BasePath,
  1096. unsigned &msg) {
  1097. // C++11 [expr.static.cast]p3:
  1098. // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
  1099. // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
  1100. const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
  1101. if (!R)
  1102. return TC_NotApplicable;
  1103. if (!SrcExpr->isGLValue())
  1104. return TC_NotApplicable;
  1105. // Because we try the reference downcast before this function, from now on
  1106. // this is the only cast possibility, so we issue an error if we fail now.
  1107. // FIXME: Should allow casting away constness if CStyle.
  1108. bool DerivedToBase;
  1109. bool ObjCConversion;
  1110. bool ObjCLifetimeConversion;
  1111. QualType FromType = SrcExpr->getType();
  1112. QualType ToType = R->getPointeeType();
  1113. if (CStyle) {
  1114. FromType = FromType.getUnqualifiedType();
  1115. ToType = ToType.getUnqualifiedType();
  1116. }
  1117. Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
  1118. SrcExpr->getLocStart(), ToType, FromType, DerivedToBase, ObjCConversion,
  1119. ObjCLifetimeConversion);
  1120. if (RefResult != Sema::Ref_Compatible) {
  1121. if (CStyle || RefResult == Sema::Ref_Incompatible)
  1122. return TC_NotApplicable;
  1123. // Diagnose types which are reference-related but not compatible here since
  1124. // we can provide better diagnostics. In these cases forwarding to
  1125. // [expr.static.cast]p4 should never result in a well-formed cast.
  1126. msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
  1127. : diag::err_bad_rvalue_to_rvalue_cast;
  1128. return TC_Failed;
  1129. }
  1130. if (DerivedToBase) {
  1131. Kind = CK_DerivedToBase;
  1132. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1133. /*DetectVirtual=*/true);
  1134. if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
  1135. R->getPointeeType(), Paths))
  1136. return TC_NotApplicable;
  1137. Self.BuildBasePathArray(Paths, BasePath);
  1138. } else
  1139. Kind = CK_NoOp;
  1140. return TC_Success;
  1141. }
  1142. /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
  1143. TryCastResult
  1144. TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
  1145. bool CStyle, SourceRange OpRange,
  1146. unsigned &msg, CastKind &Kind,
  1147. CXXCastPath &BasePath) {
  1148. // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
  1149. // cast to type "reference to cv2 D", where D is a class derived from B,
  1150. // if a valid standard conversion from "pointer to D" to "pointer to B"
  1151. // exists, cv2 >= cv1, and B is not a virtual base class of D.
  1152. // In addition, DR54 clarifies that the base must be accessible in the
  1153. // current context. Although the wording of DR54 only applies to the pointer
  1154. // variant of this rule, the intent is clearly for it to apply to the this
  1155. // conversion as well.
  1156. const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
  1157. if (!DestReference) {
  1158. return TC_NotApplicable;
  1159. }
  1160. bool RValueRef = DestReference->isRValueReferenceType();
  1161. if (!RValueRef && !SrcExpr->isLValue()) {
  1162. // We know the left side is an lvalue reference, so we can suggest a reason.
  1163. msg = diag::err_bad_cxx_cast_rvalue;
  1164. return TC_NotApplicable;
  1165. }
  1166. QualType DestPointee = DestReference->getPointeeType();
  1167. // FIXME: If the source is a prvalue, we should issue a warning (because the
  1168. // cast always has undefined behavior), and for AST consistency, we should
  1169. // materialize a temporary.
  1170. return TryStaticDowncast(Self,
  1171. Self.Context.getCanonicalType(SrcExpr->getType()),
  1172. Self.Context.getCanonicalType(DestPointee), CStyle,
  1173. OpRange, SrcExpr->getType(), DestType, msg, Kind,
  1174. BasePath);
  1175. }
  1176. /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
  1177. TryCastResult
  1178. TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
  1179. bool CStyle, SourceRange OpRange,
  1180. unsigned &msg, CastKind &Kind,
  1181. CXXCastPath &BasePath) {
  1182. // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
  1183. // type, can be converted to an rvalue of type "pointer to cv2 D", where D
  1184. // is a class derived from B, if a valid standard conversion from "pointer
  1185. // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
  1186. // class of D.
  1187. // In addition, DR54 clarifies that the base must be accessible in the
  1188. // current context.
  1189. const PointerType *DestPointer = DestType->getAs<PointerType>();
  1190. if (!DestPointer) {
  1191. return TC_NotApplicable;
  1192. }
  1193. const PointerType *SrcPointer = SrcType->getAs<PointerType>();
  1194. if (!SrcPointer) {
  1195. msg = diag::err_bad_static_cast_pointer_nonpointer;
  1196. return TC_NotApplicable;
  1197. }
  1198. return TryStaticDowncast(Self,
  1199. Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
  1200. Self.Context.getCanonicalType(DestPointer->getPointeeType()),
  1201. CStyle, OpRange, SrcType, DestType, msg, Kind,
  1202. BasePath);
  1203. }
  1204. /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
  1205. /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
  1206. /// DestType is possible and allowed.
  1207. TryCastResult
  1208. TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
  1209. bool CStyle, SourceRange OpRange, QualType OrigSrcType,
  1210. QualType OrigDestType, unsigned &msg,
  1211. CastKind &Kind, CXXCastPath &BasePath) {
  1212. // We can only work with complete types. But don't complain if it doesn't work
  1213. if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
  1214. !Self.isCompleteType(OpRange.getBegin(), DestType))
  1215. return TC_NotApplicable;
  1216. // Downcast can only happen in class hierarchies, so we need classes.
  1217. if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
  1218. return TC_NotApplicable;
  1219. }
  1220. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1221. /*DetectVirtual=*/true);
  1222. if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
  1223. return TC_NotApplicable;
  1224. }
  1225. // Target type does derive from source type. Now we're serious. If an error
  1226. // appears now, it's not ignored.
  1227. // This may not be entirely in line with the standard. Take for example:
  1228. // struct A {};
  1229. // struct B : virtual A {
  1230. // B(A&);
  1231. // };
  1232. //
  1233. // void f()
  1234. // {
  1235. // (void)static_cast<const B&>(*((A*)0));
  1236. // }
  1237. // As far as the standard is concerned, p5 does not apply (A is virtual), so
  1238. // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
  1239. // However, both GCC and Comeau reject this example, and accepting it would
  1240. // mean more complex code if we're to preserve the nice error message.
  1241. // FIXME: Being 100% compliant here would be nice to have.
  1242. // Must preserve cv, as always, unless we're in C-style mode.
  1243. if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
  1244. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1245. return TC_Failed;
  1246. }
  1247. if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
  1248. // This code is analoguous to that in CheckDerivedToBaseConversion, except
  1249. // that it builds the paths in reverse order.
  1250. // To sum up: record all paths to the base and build a nice string from
  1251. // them. Use it to spice up the error message.
  1252. if (!Paths.isRecordingPaths()) {
  1253. Paths.clear();
  1254. Paths.setRecordingPaths(true);
  1255. Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
  1256. }
  1257. std::string PathDisplayStr;
  1258. std::set<unsigned> DisplayedPaths;
  1259. for (clang::CXXBasePath &Path : Paths) {
  1260. if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
  1261. // We haven't displayed a path to this particular base
  1262. // class subobject yet.
  1263. PathDisplayStr += "\n ";
  1264. for (CXXBasePathElement &PE : llvm::reverse(Path))
  1265. PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
  1266. PathDisplayStr += QualType(DestType).getAsString();
  1267. }
  1268. }
  1269. Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
  1270. << QualType(SrcType).getUnqualifiedType()
  1271. << QualType(DestType).getUnqualifiedType()
  1272. << PathDisplayStr << OpRange;
  1273. msg = 0;
  1274. return TC_Failed;
  1275. }
  1276. if (Paths.getDetectedVirtual() != nullptr) {
  1277. QualType VirtualBase(Paths.getDetectedVirtual(), 0);
  1278. Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
  1279. << OrigSrcType << OrigDestType << VirtualBase << OpRange;
  1280. msg = 0;
  1281. return TC_Failed;
  1282. }
  1283. if (!CStyle) {
  1284. switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
  1285. SrcType, DestType,
  1286. Paths.front(),
  1287. diag::err_downcast_from_inaccessible_base)) {
  1288. case Sema::AR_accessible:
  1289. case Sema::AR_delayed: // be optimistic
  1290. case Sema::AR_dependent: // be optimistic
  1291. break;
  1292. case Sema::AR_inaccessible:
  1293. msg = 0;
  1294. return TC_Failed;
  1295. }
  1296. }
  1297. Self.BuildBasePathArray(Paths, BasePath);
  1298. Kind = CK_BaseToDerived;
  1299. return TC_Success;
  1300. }
  1301. /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
  1302. /// C++ 5.2.9p9 is valid:
  1303. ///
  1304. /// An rvalue of type "pointer to member of D of type cv1 T" can be
  1305. /// converted to an rvalue of type "pointer to member of B of type cv2 T",
  1306. /// where B is a base class of D [...].
  1307. ///
  1308. TryCastResult
  1309. TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
  1310. QualType DestType, bool CStyle,
  1311. SourceRange OpRange,
  1312. unsigned &msg, CastKind &Kind,
  1313. CXXCastPath &BasePath) {
  1314. const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
  1315. if (!DestMemPtr)
  1316. return TC_NotApplicable;
  1317. bool WasOverloadedFunction = false;
  1318. DeclAccessPair FoundOverload;
  1319. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  1320. if (FunctionDecl *Fn
  1321. = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
  1322. FoundOverload)) {
  1323. CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
  1324. SrcType = Self.Context.getMemberPointerType(Fn->getType(),
  1325. Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
  1326. WasOverloadedFunction = true;
  1327. }
  1328. }
  1329. const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
  1330. if (!SrcMemPtr) {
  1331. msg = diag::err_bad_static_cast_member_pointer_nonmp;
  1332. return TC_NotApplicable;
  1333. }
  1334. // Lock down the inheritance model right now in MS ABI, whether or not the
  1335. // pointee types are the same.
  1336. if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1337. (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
  1338. (void)Self.isCompleteType(OpRange.getBegin(), DestType);
  1339. }
  1340. // T == T, modulo cv
  1341. if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
  1342. DestMemPtr->getPointeeType()))
  1343. return TC_NotApplicable;
  1344. // B base of D
  1345. QualType SrcClass(SrcMemPtr->getClass(), 0);
  1346. QualType DestClass(DestMemPtr->getClass(), 0);
  1347. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1348. /*DetectVirtual=*/true);
  1349. if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
  1350. return TC_NotApplicable;
  1351. // B is a base of D. But is it an allowed base? If not, it's a hard error.
  1352. if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
  1353. Paths.clear();
  1354. Paths.setRecordingPaths(true);
  1355. bool StillOkay =
  1356. Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
  1357. assert(StillOkay);
  1358. (void)StillOkay;
  1359. std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
  1360. Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
  1361. << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
  1362. msg = 0;
  1363. return TC_Failed;
  1364. }
  1365. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  1366. Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
  1367. << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
  1368. msg = 0;
  1369. return TC_Failed;
  1370. }
  1371. if (!CStyle) {
  1372. switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
  1373. DestClass, SrcClass,
  1374. Paths.front(),
  1375. diag::err_upcast_to_inaccessible_base)) {
  1376. case Sema::AR_accessible:
  1377. case Sema::AR_delayed:
  1378. case Sema::AR_dependent:
  1379. // Optimistically assume that the delayed and dependent cases
  1380. // will work out.
  1381. break;
  1382. case Sema::AR_inaccessible:
  1383. msg = 0;
  1384. return TC_Failed;
  1385. }
  1386. }
  1387. if (WasOverloadedFunction) {
  1388. // Resolve the address of the overloaded function again, this time
  1389. // allowing complaints if something goes wrong.
  1390. FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
  1391. DestType,
  1392. true,
  1393. FoundOverload);
  1394. if (!Fn) {
  1395. msg = 0;
  1396. return TC_Failed;
  1397. }
  1398. SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
  1399. if (!SrcExpr.isUsable()) {
  1400. msg = 0;
  1401. return TC_Failed;
  1402. }
  1403. }
  1404. Self.BuildBasePathArray(Paths, BasePath);
  1405. Kind = CK_DerivedToBaseMemberPointer;
  1406. return TC_Success;
  1407. }
  1408. /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
  1409. /// is valid:
  1410. ///
  1411. /// An expression e can be explicitly converted to a type T using a
  1412. /// @c static_cast if the declaration "T t(e);" is well-formed [...].
  1413. TryCastResult
  1414. TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
  1415. Sema::CheckedConversionKind CCK,
  1416. SourceRange OpRange, unsigned &msg,
  1417. CastKind &Kind, bool ListInitialization) {
  1418. if (DestType->isRecordType()) {
  1419. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  1420. diag::err_bad_dynamic_cast_incomplete) ||
  1421. Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
  1422. diag::err_allocation_of_abstract_type)) {
  1423. msg = 0;
  1424. return TC_Failed;
  1425. }
  1426. }
  1427. InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
  1428. InitializationKind InitKind
  1429. = (CCK == Sema::CCK_CStyleCast)
  1430. ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
  1431. ListInitialization)
  1432. : (CCK == Sema::CCK_FunctionalCast)
  1433. ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
  1434. : InitializationKind::CreateCast(OpRange);
  1435. Expr *SrcExprRaw = SrcExpr.get();
  1436. // FIXME: Per DR242, we should check for an implicit conversion sequence
  1437. // or for a constructor that could be invoked by direct-initialization
  1438. // here, not for an initialization sequence.
  1439. InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
  1440. // At this point of CheckStaticCast, if the destination is a reference,
  1441. // or the expression is an overload expression this has to work.
  1442. // There is no other way that works.
  1443. // On the other hand, if we're checking a C-style cast, we've still got
  1444. // the reinterpret_cast way.
  1445. bool CStyle
  1446. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  1447. if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
  1448. return TC_NotApplicable;
  1449. ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
  1450. if (Result.isInvalid()) {
  1451. msg = 0;
  1452. return TC_Failed;
  1453. }
  1454. if (InitSeq.isConstructorInitialization())
  1455. Kind = CK_ConstructorConversion;
  1456. else
  1457. Kind = CK_NoOp;
  1458. SrcExpr = Result;
  1459. return TC_Success;
  1460. }
  1461. /// TryConstCast - See if a const_cast from source to destination is allowed,
  1462. /// and perform it if it is.
  1463. static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
  1464. QualType DestType, bool CStyle,
  1465. unsigned &msg) {
  1466. DestType = Self.Context.getCanonicalType(DestType);
  1467. QualType SrcType = SrcExpr.get()->getType();
  1468. bool NeedToMaterializeTemporary = false;
  1469. if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
  1470. // C++11 5.2.11p4:
  1471. // if a pointer to T1 can be explicitly converted to the type "pointer to
  1472. // T2" using a const_cast, then the following conversions can also be
  1473. // made:
  1474. // -- an lvalue of type T1 can be explicitly converted to an lvalue of
  1475. // type T2 using the cast const_cast<T2&>;
  1476. // -- a glvalue of type T1 can be explicitly converted to an xvalue of
  1477. // type T2 using the cast const_cast<T2&&>; and
  1478. // -- if T1 is a class type, a prvalue of type T1 can be explicitly
  1479. // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
  1480. if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
  1481. // Cannot const_cast non-lvalue to lvalue reference type. But if this
  1482. // is C-style, static_cast might find a way, so we simply suggest a
  1483. // message and tell the parent to keep searching.
  1484. msg = diag::err_bad_cxx_cast_rvalue;
  1485. return TC_NotApplicable;
  1486. }
  1487. if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
  1488. if (!SrcType->isRecordType()) {
  1489. // Cannot const_cast non-class prvalue to rvalue reference type. But if
  1490. // this is C-style, static_cast can do this.
  1491. msg = diag::err_bad_cxx_cast_rvalue;
  1492. return TC_NotApplicable;
  1493. }
  1494. // Materialize the class prvalue so that the const_cast can bind a
  1495. // reference to it.
  1496. NeedToMaterializeTemporary = true;
  1497. }
  1498. // It's not completely clear under the standard whether we can
  1499. // const_cast bit-field gl-values. Doing so would not be
  1500. // intrinsically complicated, but for now, we say no for
  1501. // consistency with other compilers and await the word of the
  1502. // committee.
  1503. if (SrcExpr.get()->refersToBitField()) {
  1504. msg = diag::err_bad_cxx_cast_bitfield;
  1505. return TC_NotApplicable;
  1506. }
  1507. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
  1508. SrcType = Self.Context.getPointerType(SrcType);
  1509. }
  1510. // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
  1511. // the rules for const_cast are the same as those used for pointers.
  1512. if (!DestType->isPointerType() &&
  1513. !DestType->isMemberPointerType() &&
  1514. !DestType->isObjCObjectPointerType()) {
  1515. // Cannot cast to non-pointer, non-reference type. Note that, if DestType
  1516. // was a reference type, we converted it to a pointer above.
  1517. // The status of rvalue references isn't entirely clear, but it looks like
  1518. // conversion to them is simply invalid.
  1519. // C++ 5.2.11p3: For two pointer types [...]
  1520. if (!CStyle)
  1521. msg = diag::err_bad_const_cast_dest;
  1522. return TC_NotApplicable;
  1523. }
  1524. if (DestType->isFunctionPointerType() ||
  1525. DestType->isMemberFunctionPointerType()) {
  1526. // Cannot cast direct function pointers.
  1527. // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
  1528. // T is the ultimate pointee of source and target type.
  1529. if (!CStyle)
  1530. msg = diag::err_bad_const_cast_dest;
  1531. return TC_NotApplicable;
  1532. }
  1533. // C++ [expr.const.cast]p3:
  1534. // "For two similar types T1 and T2, [...]"
  1535. //
  1536. // We only allow a const_cast to change cvr-qualifiers, not other kinds of
  1537. // type qualifiers. (Likewise, we ignore other changes when determining
  1538. // whether a cast casts away constness.)
  1539. if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
  1540. return TC_NotApplicable;
  1541. if (NeedToMaterializeTemporary)
  1542. // This is a const_cast from a class prvalue to an rvalue reference type.
  1543. // Materialize a temporary to store the result of the conversion.
  1544. SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
  1545. SrcExpr.get(),
  1546. /*IsLValueReference*/ false);
  1547. return TC_Success;
  1548. }
  1549. // Checks for undefined behavior in reinterpret_cast.
  1550. // The cases that is checked for is:
  1551. // *reinterpret_cast<T*>(&a)
  1552. // reinterpret_cast<T&>(a)
  1553. // where accessing 'a' as type 'T' will result in undefined behavior.
  1554. void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
  1555. bool IsDereference,
  1556. SourceRange Range) {
  1557. unsigned DiagID = IsDereference ?
  1558. diag::warn_pointer_indirection_from_incompatible_type :
  1559. diag::warn_undefined_reinterpret_cast;
  1560. if (Diags.isIgnored(DiagID, Range.getBegin()))
  1561. return;
  1562. QualType SrcTy, DestTy;
  1563. if (IsDereference) {
  1564. if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
  1565. return;
  1566. }
  1567. SrcTy = SrcType->getPointeeType();
  1568. DestTy = DestType->getPointeeType();
  1569. } else {
  1570. if (!DestType->getAs<ReferenceType>()) {
  1571. return;
  1572. }
  1573. SrcTy = SrcType;
  1574. DestTy = DestType->getPointeeType();
  1575. }
  1576. // Cast is compatible if the types are the same.
  1577. if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
  1578. return;
  1579. }
  1580. // or one of the types is a char or void type
  1581. if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
  1582. SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
  1583. return;
  1584. }
  1585. // or one of the types is a tag type.
  1586. if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
  1587. return;
  1588. }
  1589. // FIXME: Scoped enums?
  1590. if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
  1591. (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
  1592. if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
  1593. return;
  1594. }
  1595. }
  1596. Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
  1597. }
  1598. static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
  1599. QualType DestType) {
  1600. QualType SrcType = SrcExpr.get()->getType();
  1601. if (Self.Context.hasSameType(SrcType, DestType))
  1602. return;
  1603. if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
  1604. if (SrcPtrTy->isObjCSelType()) {
  1605. QualType DT = DestType;
  1606. if (isa<PointerType>(DestType))
  1607. DT = DestType->getPointeeType();
  1608. if (!DT.getUnqualifiedType()->isVoidType())
  1609. Self.Diag(SrcExpr.get()->getExprLoc(),
  1610. diag::warn_cast_pointer_from_sel)
  1611. << SrcType << DestType << SrcExpr.get()->getSourceRange();
  1612. }
  1613. }
  1614. /// Diagnose casts that change the calling convention of a pointer to a function
  1615. /// defined in the current TU.
  1616. static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
  1617. QualType DstType, SourceRange OpRange) {
  1618. // Check if this cast would change the calling convention of a function
  1619. // pointer type.
  1620. QualType SrcType = SrcExpr.get()->getType();
  1621. if (Self.Context.hasSameType(SrcType, DstType) ||
  1622. !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
  1623. return;
  1624. const auto *SrcFTy =
  1625. SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
  1626. const auto *DstFTy =
  1627. DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
  1628. CallingConv SrcCC = SrcFTy->getCallConv();
  1629. CallingConv DstCC = DstFTy->getCallConv();
  1630. if (SrcCC == DstCC)
  1631. return;
  1632. // We have a calling convention cast. Check if the source is a pointer to a
  1633. // known, specific function that has already been defined.
  1634. Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
  1635. if (auto *UO = dyn_cast<UnaryOperator>(Src))
  1636. if (UO->getOpcode() == UO_AddrOf)
  1637. Src = UO->getSubExpr()->IgnoreParenImpCasts();
  1638. auto *DRE = dyn_cast<DeclRefExpr>(Src);
  1639. if (!DRE)
  1640. return;
  1641. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  1642. if (!FD)
  1643. return;
  1644. // Only warn if we are casting from the default convention to a non-default
  1645. // convention. This can happen when the programmer forgot to apply the calling
  1646. // convention to the function declaration and then inserted this cast to
  1647. // satisfy the type system.
  1648. CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
  1649. FD->isVariadic(), FD->isCXXInstanceMember());
  1650. if (DstCC == DefaultCC || SrcCC != DefaultCC)
  1651. return;
  1652. // Diagnose this cast, as it is probably bad.
  1653. StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
  1654. StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
  1655. Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
  1656. << SrcCCName << DstCCName << OpRange;
  1657. // The checks above are cheaper than checking if the diagnostic is enabled.
  1658. // However, it's worth checking if the warning is enabled before we construct
  1659. // a fixit.
  1660. if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
  1661. return;
  1662. // Try to suggest a fixit to change the calling convention of the function
  1663. // whose address was taken. Try to use the latest macro for the convention.
  1664. // For example, users probably want to write "WINAPI" instead of "__stdcall"
  1665. // to match the Windows header declarations.
  1666. SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
  1667. Preprocessor &PP = Self.getPreprocessor();
  1668. SmallVector<TokenValue, 6> AttrTokens;
  1669. SmallString<64> CCAttrText;
  1670. llvm::raw_svector_ostream OS(CCAttrText);
  1671. if (Self.getLangOpts().MicrosoftExt) {
  1672. // __stdcall or __vectorcall
  1673. OS << "__" << DstCCName;
  1674. IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
  1675. AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
  1676. ? TokenValue(II->getTokenID())
  1677. : TokenValue(II));
  1678. } else {
  1679. // __attribute__((stdcall)) or __attribute__((vectorcall))
  1680. OS << "__attribute__((" << DstCCName << "))";
  1681. AttrTokens.push_back(tok::kw___attribute);
  1682. AttrTokens.push_back(tok::l_paren);
  1683. AttrTokens.push_back(tok::l_paren);
  1684. IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
  1685. AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
  1686. ? TokenValue(II->getTokenID())
  1687. : TokenValue(II));
  1688. AttrTokens.push_back(tok::r_paren);
  1689. AttrTokens.push_back(tok::r_paren);
  1690. }
  1691. StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
  1692. if (!AttrSpelling.empty())
  1693. CCAttrText = AttrSpelling;
  1694. OS << ' ';
  1695. Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
  1696. << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
  1697. }
  1698. static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
  1699. const Expr *SrcExpr, QualType DestType,
  1700. Sema &Self) {
  1701. QualType SrcType = SrcExpr->getType();
  1702. // Not warning on reinterpret_cast, boolean, constant expressions, etc
  1703. // are not explicit design choices, but consistent with GCC's behavior.
  1704. // Feel free to modify them if you've reason/evidence for an alternative.
  1705. if (CStyle && SrcType->isIntegralType(Self.Context)
  1706. && !SrcType->isBooleanType()
  1707. && !SrcType->isEnumeralType()
  1708. && !SrcExpr->isIntegerConstantExpr(Self.Context)
  1709. && Self.Context.getTypeSize(DestType) >
  1710. Self.Context.getTypeSize(SrcType)) {
  1711. // Separate between casts to void* and non-void* pointers.
  1712. // Some APIs use (abuse) void* for something like a user context,
  1713. // and often that value is an integer even if it isn't a pointer itself.
  1714. // Having a separate warning flag allows users to control the warning
  1715. // for their workflow.
  1716. unsigned Diag = DestType->isVoidPointerType() ?
  1717. diag::warn_int_to_void_pointer_cast
  1718. : diag::warn_int_to_pointer_cast;
  1719. Self.Diag(Loc, Diag) << SrcType << DestType;
  1720. }
  1721. }
  1722. static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
  1723. ExprResult &Result) {
  1724. // We can only fix an overloaded reinterpret_cast if
  1725. // - it is a template with explicit arguments that resolves to an lvalue
  1726. // unambiguously, or
  1727. // - it is the only function in an overload set that may have its address
  1728. // taken.
  1729. Expr *E = Result.get();
  1730. // TODO: what if this fails because of DiagnoseUseOfDecl or something
  1731. // like it?
  1732. if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
  1733. Result,
  1734. Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
  1735. ) &&
  1736. Result.isUsable())
  1737. return true;
  1738. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  1739. // preserves Result.
  1740. Result = E;
  1741. if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
  1742. Result, /*DoFunctionPointerConversion=*/true))
  1743. return false;
  1744. return Result.isUsable();
  1745. }
  1746. static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
  1747. return SrcType->isPointerType() && DestType->isPointerType() &&
  1748. SrcType->getAs<PointerType>()->getPointeeType().getAddressSpace() !=
  1749. DestType->getAs<PointerType>()->getPointeeType().getAddressSpace();
  1750. }
  1751. static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
  1752. QualType DestType, bool CStyle,
  1753. SourceRange OpRange,
  1754. unsigned &msg,
  1755. CastKind &Kind) {
  1756. bool IsLValueCast = false;
  1757. DestType = Self.Context.getCanonicalType(DestType);
  1758. QualType SrcType = SrcExpr.get()->getType();
  1759. // Is the source an overloaded name? (i.e. &foo)
  1760. // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
  1761. if (SrcType == Self.Context.OverloadTy) {
  1762. ExprResult FixedExpr = SrcExpr;
  1763. if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
  1764. return TC_NotApplicable;
  1765. assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
  1766. SrcExpr = FixedExpr;
  1767. SrcType = SrcExpr.get()->getType();
  1768. }
  1769. if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
  1770. if (!SrcExpr.get()->isGLValue()) {
  1771. // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
  1772. // similar comment in const_cast.
  1773. msg = diag::err_bad_cxx_cast_rvalue;
  1774. return TC_NotApplicable;
  1775. }
  1776. if (!CStyle) {
  1777. Self.CheckCompatibleReinterpretCast(SrcType, DestType,
  1778. /*isDereference=*/false, OpRange);
  1779. }
  1780. // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
  1781. // same effect as the conversion *reinterpret_cast<T*>(&x) with the
  1782. // built-in & and * operators.
  1783. const char *inappropriate = nullptr;
  1784. switch (SrcExpr.get()->getObjectKind()) {
  1785. case OK_Ordinary:
  1786. break;
  1787. case OK_BitField:
  1788. msg = diag::err_bad_cxx_cast_bitfield;
  1789. return TC_NotApplicable;
  1790. // FIXME: Use a specific diagnostic for the rest of these cases.
  1791. case OK_VectorComponent: inappropriate = "vector element"; break;
  1792. case OK_ObjCProperty: inappropriate = "property expression"; break;
  1793. case OK_ObjCSubscript: inappropriate = "container subscripting expression";
  1794. break;
  1795. }
  1796. if (inappropriate) {
  1797. Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
  1798. << inappropriate << DestType
  1799. << OpRange << SrcExpr.get()->getSourceRange();
  1800. msg = 0; SrcExpr = ExprError();
  1801. return TC_NotApplicable;
  1802. }
  1803. // This code does this transformation for the checked types.
  1804. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
  1805. SrcType = Self.Context.getPointerType(SrcType);
  1806. IsLValueCast = true;
  1807. }
  1808. // Canonicalize source for comparison.
  1809. SrcType = Self.Context.getCanonicalType(SrcType);
  1810. const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
  1811. *SrcMemPtr = SrcType->getAs<MemberPointerType>();
  1812. if (DestMemPtr && SrcMemPtr) {
  1813. // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
  1814. // can be explicitly converted to an rvalue of type "pointer to member
  1815. // of Y of type T2" if T1 and T2 are both function types or both object
  1816. // types.
  1817. if (DestMemPtr->isMemberFunctionPointer() !=
  1818. SrcMemPtr->isMemberFunctionPointer())
  1819. return TC_NotApplicable;
  1820. if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1821. // We need to determine the inheritance model that the class will use if
  1822. // haven't yet.
  1823. (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
  1824. (void)Self.isCompleteType(OpRange.getBegin(), DestType);
  1825. }
  1826. // Don't allow casting between member pointers of different sizes.
  1827. if (Self.Context.getTypeSize(DestMemPtr) !=
  1828. Self.Context.getTypeSize(SrcMemPtr)) {
  1829. msg = diag::err_bad_cxx_cast_member_pointer_size;
  1830. return TC_Failed;
  1831. }
  1832. // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
  1833. // constness.
  1834. // A reinterpret_cast followed by a const_cast can, though, so in C-style,
  1835. // we accept it.
  1836. if (auto CACK =
  1837. CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
  1838. /*CheckObjCLifetime=*/CStyle))
  1839. return getCastAwayConstnessCastKind(CACK, msg);
  1840. // A valid member pointer cast.
  1841. assert(!IsLValueCast);
  1842. Kind = CK_ReinterpretMemberPointer;
  1843. return TC_Success;
  1844. }
  1845. // See below for the enumeral issue.
  1846. if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
  1847. // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
  1848. // type large enough to hold it. A value of std::nullptr_t can be
  1849. // converted to an integral type; the conversion has the same meaning
  1850. // and validity as a conversion of (void*)0 to the integral type.
  1851. if (Self.Context.getTypeSize(SrcType) >
  1852. Self.Context.getTypeSize(DestType)) {
  1853. msg = diag::err_bad_reinterpret_cast_small_int;
  1854. return TC_Failed;
  1855. }
  1856. Kind = CK_PointerToIntegral;
  1857. return TC_Success;
  1858. }
  1859. // Allow reinterpret_casts between vectors of the same size and
  1860. // between vectors and integers of the same size.
  1861. bool destIsVector = DestType->isVectorType();
  1862. bool srcIsVector = SrcType->isVectorType();
  1863. if (srcIsVector || destIsVector) {
  1864. // The non-vector type, if any, must have integral type. This is
  1865. // the same rule that C vector casts use; note, however, that enum
  1866. // types are not integral in C++.
  1867. if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
  1868. (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
  1869. return TC_NotApplicable;
  1870. // The size we want to consider is eltCount * eltSize.
  1871. // That's exactly what the lax-conversion rules will check.
  1872. if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
  1873. Kind = CK_BitCast;
  1874. return TC_Success;
  1875. }
  1876. // Otherwise, pick a reasonable diagnostic.
  1877. if (!destIsVector)
  1878. msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
  1879. else if (!srcIsVector)
  1880. msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
  1881. else
  1882. msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
  1883. return TC_Failed;
  1884. }
  1885. if (SrcType == DestType) {
  1886. // C++ 5.2.10p2 has a note that mentions that, subject to all other
  1887. // restrictions, a cast to the same type is allowed so long as it does not
  1888. // cast away constness. In C++98, the intent was not entirely clear here,
  1889. // since all other paragraphs explicitly forbid casts to the same type.
  1890. // C++11 clarifies this case with p2.
  1891. //
  1892. // The only allowed types are: integral, enumeration, pointer, or
  1893. // pointer-to-member types. We also won't restrict Obj-C pointers either.
  1894. Kind = CK_NoOp;
  1895. TryCastResult Result = TC_NotApplicable;
  1896. if (SrcType->isIntegralOrEnumerationType() ||
  1897. SrcType->isAnyPointerType() ||
  1898. SrcType->isMemberPointerType() ||
  1899. SrcType->isBlockPointerType()) {
  1900. Result = TC_Success;
  1901. }
  1902. return Result;
  1903. }
  1904. bool destIsPtr = DestType->isAnyPointerType() ||
  1905. DestType->isBlockPointerType();
  1906. bool srcIsPtr = SrcType->isAnyPointerType() ||
  1907. SrcType->isBlockPointerType();
  1908. if (!destIsPtr && !srcIsPtr) {
  1909. // Except for std::nullptr_t->integer and lvalue->reference, which are
  1910. // handled above, at least one of the two arguments must be a pointer.
  1911. return TC_NotApplicable;
  1912. }
  1913. if (DestType->isIntegralType(Self.Context)) {
  1914. assert(srcIsPtr && "One type must be a pointer");
  1915. // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
  1916. // type large enough to hold it; except in Microsoft mode, where the
  1917. // integral type size doesn't matter (except we don't allow bool).
  1918. bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
  1919. !DestType->isBooleanType();
  1920. if ((Self.Context.getTypeSize(SrcType) >
  1921. Self.Context.getTypeSize(DestType)) &&
  1922. !MicrosoftException) {
  1923. msg = diag::err_bad_reinterpret_cast_small_int;
  1924. return TC_Failed;
  1925. }
  1926. Kind = CK_PointerToIntegral;
  1927. return TC_Success;
  1928. }
  1929. if (SrcType->isIntegralOrEnumerationType()) {
  1930. assert(destIsPtr && "One type must be a pointer");
  1931. checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
  1932. Self);
  1933. // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
  1934. // converted to a pointer.
  1935. // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
  1936. // necessarily converted to a null pointer value.]
  1937. Kind = CK_IntegralToPointer;
  1938. return TC_Success;
  1939. }
  1940. if (!destIsPtr || !srcIsPtr) {
  1941. // With the valid non-pointer conversions out of the way, we can be even
  1942. // more stringent.
  1943. return TC_NotApplicable;
  1944. }
  1945. // Cannot convert between block pointers and Objective-C object pointers.
  1946. if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
  1947. (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
  1948. return TC_NotApplicable;
  1949. // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
  1950. // The C-style cast operator can.
  1951. TryCastResult SuccessResult = TC_Success;
  1952. if (auto CACK =
  1953. CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
  1954. /*CheckObjCLifetime=*/CStyle))
  1955. SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
  1956. if (IsLValueCast) {
  1957. Kind = CK_LValueBitCast;
  1958. } else if (DestType->isObjCObjectPointerType()) {
  1959. Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
  1960. } else if (DestType->isBlockPointerType()) {
  1961. if (!SrcType->isBlockPointerType()) {
  1962. Kind = CK_AnyPointerToBlockPointerCast;
  1963. } else {
  1964. Kind = CK_BitCast;
  1965. }
  1966. } else if (IsAddressSpaceConversion(SrcType, DestType)) {
  1967. Kind = CK_AddressSpaceConversion;
  1968. } else {
  1969. Kind = CK_BitCast;
  1970. }
  1971. // Any pointer can be cast to an Objective-C pointer type with a C-style
  1972. // cast.
  1973. if (CStyle && DestType->isObjCObjectPointerType()) {
  1974. return SuccessResult;
  1975. }
  1976. if (CStyle)
  1977. DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
  1978. DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
  1979. // Not casting away constness, so the only remaining check is for compatible
  1980. // pointer categories.
  1981. if (SrcType->isFunctionPointerType()) {
  1982. if (DestType->isFunctionPointerType()) {
  1983. // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
  1984. // a pointer to a function of a different type.
  1985. return SuccessResult;
  1986. }
  1987. // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
  1988. // an object type or vice versa is conditionally-supported.
  1989. // Compilers support it in C++03 too, though, because it's necessary for
  1990. // casting the return value of dlsym() and GetProcAddress().
  1991. // FIXME: Conditionally-supported behavior should be configurable in the
  1992. // TargetInfo or similar.
  1993. Self.Diag(OpRange.getBegin(),
  1994. Self.getLangOpts().CPlusPlus11 ?
  1995. diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
  1996. << OpRange;
  1997. return SuccessResult;
  1998. }
  1999. if (DestType->isFunctionPointerType()) {
  2000. // See above.
  2001. Self.Diag(OpRange.getBegin(),
  2002. Self.getLangOpts().CPlusPlus11 ?
  2003. diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
  2004. << OpRange;
  2005. return SuccessResult;
  2006. }
  2007. // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
  2008. // a pointer to an object of different type.
  2009. // Void pointers are not specified, but supported by every compiler out there.
  2010. // So we finish by allowing everything that remains - it's got to be two
  2011. // object pointers.
  2012. return SuccessResult;
  2013. }
  2014. void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
  2015. bool ListInitialization) {
  2016. assert(Self.getLangOpts().CPlusPlus);
  2017. // Handle placeholders.
  2018. if (isPlaceholder()) {
  2019. // C-style casts can resolve __unknown_any types.
  2020. if (claimPlaceholder(BuiltinType::UnknownAny)) {
  2021. SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
  2022. SrcExpr.get(), Kind,
  2023. ValueKind, BasePath);
  2024. return;
  2025. }
  2026. checkNonOverloadPlaceholders();
  2027. if (SrcExpr.isInvalid())
  2028. return;
  2029. }
  2030. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  2031. // This test is outside everything else because it's the only case where
  2032. // a non-lvalue-reference target type does not lead to decay.
  2033. if (DestType->isVoidType()) {
  2034. Kind = CK_ToVoid;
  2035. if (claimPlaceholder(BuiltinType::Overload)) {
  2036. Self.ResolveAndFixSingleFunctionTemplateSpecialization(
  2037. SrcExpr, /* Decay Function to ptr */ false,
  2038. /* Complain */ true, DestRange, DestType,
  2039. diag::err_bad_cstyle_cast_overload);
  2040. if (SrcExpr.isInvalid())
  2041. return;
  2042. }
  2043. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  2044. return;
  2045. }
  2046. // If the type is dependent, we won't do any other semantic analysis now.
  2047. if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
  2048. SrcExpr.get()->isValueDependent()) {
  2049. assert(Kind == CK_Dependent);
  2050. return;
  2051. }
  2052. if (ValueKind == VK_RValue && !DestType->isRecordType() &&
  2053. !isPlaceholder(BuiltinType::Overload)) {
  2054. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  2055. if (SrcExpr.isInvalid())
  2056. return;
  2057. }
  2058. // AltiVec vector initialization with a single literal.
  2059. if (const VectorType *vecTy = DestType->getAs<VectorType>())
  2060. if (vecTy->getVectorKind() == VectorType::AltiVecVector
  2061. && (SrcExpr.get()->getType()->isIntegerType()
  2062. || SrcExpr.get()->getType()->isFloatingType())) {
  2063. Kind = CK_VectorSplat;
  2064. SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
  2065. return;
  2066. }
  2067. // C++ [expr.cast]p5: The conversions performed by
  2068. // - a const_cast,
  2069. // - a static_cast,
  2070. // - a static_cast followed by a const_cast,
  2071. // - a reinterpret_cast, or
  2072. // - a reinterpret_cast followed by a const_cast,
  2073. // can be performed using the cast notation of explicit type conversion.
  2074. // [...] If a conversion can be interpreted in more than one of the ways
  2075. // listed above, the interpretation that appears first in the list is used,
  2076. // even if a cast resulting from that interpretation is ill-formed.
  2077. // In plain language, this means trying a const_cast ...
  2078. unsigned msg = diag::err_bad_cxx_cast_generic;
  2079. TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
  2080. /*CStyle*/true, msg);
  2081. if (SrcExpr.isInvalid())
  2082. return;
  2083. if (isValidCast(tcr))
  2084. Kind = CK_NoOp;
  2085. Sema::CheckedConversionKind CCK
  2086. = FunctionalStyle? Sema::CCK_FunctionalCast
  2087. : Sema::CCK_CStyleCast;
  2088. if (tcr == TC_NotApplicable) {
  2089. // ... or if that is not possible, a static_cast, ignoring const, ...
  2090. tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
  2091. msg, Kind, BasePath, ListInitialization);
  2092. if (SrcExpr.isInvalid())
  2093. return;
  2094. if (tcr == TC_NotApplicable) {
  2095. // ... and finally a reinterpret_cast, ignoring const.
  2096. tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
  2097. OpRange, msg, Kind);
  2098. if (SrcExpr.isInvalid())
  2099. return;
  2100. }
  2101. }
  2102. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  2103. isValidCast(tcr))
  2104. checkObjCConversion(CCK);
  2105. if (tcr != TC_Success && msg != 0) {
  2106. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  2107. DeclAccessPair Found;
  2108. FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
  2109. DestType,
  2110. /*Complain*/ true,
  2111. Found);
  2112. if (Fn) {
  2113. // If DestType is a function type (not to be confused with the function
  2114. // pointer type), it will be possible to resolve the function address,
  2115. // but the type cast should be considered as failure.
  2116. OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
  2117. Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
  2118. << OE->getName() << DestType << OpRange
  2119. << OE->getQualifierLoc().getSourceRange();
  2120. Self.NoteAllOverloadCandidates(SrcExpr.get());
  2121. }
  2122. } else {
  2123. diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
  2124. OpRange, SrcExpr.get(), DestType, ListInitialization);
  2125. }
  2126. }
  2127. if (isValidCast(tcr)) {
  2128. if (Kind == CK_BitCast)
  2129. checkCastAlign();
  2130. } else {
  2131. SrcExpr = ExprError();
  2132. }
  2133. }
  2134. /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
  2135. /// non-matching type. Such as enum function call to int, int call to
  2136. /// pointer; etc. Cast to 'void' is an exception.
  2137. static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
  2138. QualType DestType) {
  2139. if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
  2140. SrcExpr.get()->getExprLoc()))
  2141. return;
  2142. if (!isa<CallExpr>(SrcExpr.get()))
  2143. return;
  2144. QualType SrcType = SrcExpr.get()->getType();
  2145. if (DestType.getUnqualifiedType()->isVoidType())
  2146. return;
  2147. if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
  2148. && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
  2149. return;
  2150. if (SrcType->isIntegerType() && DestType->isIntegerType() &&
  2151. (SrcType->isBooleanType() == DestType->isBooleanType()) &&
  2152. (SrcType->isEnumeralType() == DestType->isEnumeralType()))
  2153. return;
  2154. if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
  2155. return;
  2156. if (SrcType->isEnumeralType() && DestType->isEnumeralType())
  2157. return;
  2158. if (SrcType->isComplexType() && DestType->isComplexType())
  2159. return;
  2160. if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
  2161. return;
  2162. Self.Diag(SrcExpr.get()->getExprLoc(),
  2163. diag::warn_bad_function_cast)
  2164. << SrcType << DestType << SrcExpr.get()->getSourceRange();
  2165. }
  2166. /// Check the semantics of a C-style cast operation, in C.
  2167. void CastOperation::CheckCStyleCast() {
  2168. assert(!Self.getLangOpts().CPlusPlus);
  2169. // C-style casts can resolve __unknown_any types.
  2170. if (claimPlaceholder(BuiltinType::UnknownAny)) {
  2171. SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
  2172. SrcExpr.get(), Kind,
  2173. ValueKind, BasePath);
  2174. return;
  2175. }
  2176. // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
  2177. // type needs to be scalar.
  2178. if (DestType->isVoidType()) {
  2179. // We don't necessarily do lvalue-to-rvalue conversions on this.
  2180. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  2181. if (SrcExpr.isInvalid())
  2182. return;
  2183. // Cast to void allows any expr type.
  2184. Kind = CK_ToVoid;
  2185. return;
  2186. }
  2187. // Overloads are allowed with C extensions, so we need to support them.
  2188. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  2189. DeclAccessPair DAP;
  2190. if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
  2191. SrcExpr.get(), DestType, /*Complain=*/true, DAP))
  2192. SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
  2193. else
  2194. return;
  2195. assert(SrcExpr.isUsable());
  2196. }
  2197. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  2198. if (SrcExpr.isInvalid())
  2199. return;
  2200. QualType SrcType = SrcExpr.get()->getType();
  2201. assert(!SrcType->isPlaceholderType());
  2202. // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
  2203. // address space B is illegal.
  2204. if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
  2205. SrcType->isPointerType()) {
  2206. const PointerType *DestPtr = DestType->getAs<PointerType>();
  2207. if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
  2208. Self.Diag(OpRange.getBegin(),
  2209. diag::err_typecheck_incompatible_address_space)
  2210. << SrcType << DestType << Sema::AA_Casting
  2211. << SrcExpr.get()->getSourceRange();
  2212. SrcExpr = ExprError();
  2213. return;
  2214. }
  2215. }
  2216. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  2217. diag::err_typecheck_cast_to_incomplete)) {
  2218. SrcExpr = ExprError();
  2219. return;
  2220. }
  2221. if (!DestType->isScalarType() && !DestType->isVectorType()) {
  2222. const RecordType *DestRecordTy = DestType->getAs<RecordType>();
  2223. if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
  2224. // GCC struct/union extension: allow cast to self.
  2225. Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
  2226. << DestType << SrcExpr.get()->getSourceRange();
  2227. Kind = CK_NoOp;
  2228. return;
  2229. }
  2230. // GCC's cast to union extension.
  2231. if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
  2232. RecordDecl *RD = DestRecordTy->getDecl();
  2233. if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
  2234. Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
  2235. << SrcExpr.get()->getSourceRange();
  2236. Kind = CK_ToUnion;
  2237. return;
  2238. } else {
  2239. Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
  2240. << SrcType << SrcExpr.get()->getSourceRange();
  2241. SrcExpr = ExprError();
  2242. return;
  2243. }
  2244. }
  2245. // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
  2246. if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
  2247. llvm::APSInt CastInt;
  2248. if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) {
  2249. if (0 == CastInt) {
  2250. Kind = CK_ZeroToOCLEvent;
  2251. return;
  2252. }
  2253. Self.Diag(OpRange.getBegin(),
  2254. diag::err_opencl_cast_non_zero_to_event_t)
  2255. << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
  2256. SrcExpr = ExprError();
  2257. return;
  2258. }
  2259. }
  2260. // Reject any other conversions to non-scalar types.
  2261. Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
  2262. << DestType << SrcExpr.get()->getSourceRange();
  2263. SrcExpr = ExprError();
  2264. return;
  2265. }
  2266. // The type we're casting to is known to be a scalar or vector.
  2267. // Require the operand to be a scalar or vector.
  2268. if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
  2269. Self.Diag(SrcExpr.get()->getExprLoc(),
  2270. diag::err_typecheck_expect_scalar_operand)
  2271. << SrcType << SrcExpr.get()->getSourceRange();
  2272. SrcExpr = ExprError();
  2273. return;
  2274. }
  2275. if (DestType->isExtVectorType()) {
  2276. SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
  2277. return;
  2278. }
  2279. if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
  2280. if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
  2281. (SrcType->isIntegerType() || SrcType->isFloatingType())) {
  2282. Kind = CK_VectorSplat;
  2283. SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
  2284. } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
  2285. SrcExpr = ExprError();
  2286. }
  2287. return;
  2288. }
  2289. if (SrcType->isVectorType()) {
  2290. if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
  2291. SrcExpr = ExprError();
  2292. return;
  2293. }
  2294. // The source and target types are both scalars, i.e.
  2295. // - arithmetic types (fundamental, enum, and complex)
  2296. // - all kinds of pointers
  2297. // Note that member pointers were filtered out with C++, above.
  2298. if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
  2299. Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
  2300. SrcExpr = ExprError();
  2301. return;
  2302. }
  2303. // If either type is a pointer, the other type has to be either an
  2304. // integer or a pointer.
  2305. if (!DestType->isArithmeticType()) {
  2306. if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
  2307. Self.Diag(SrcExpr.get()->getExprLoc(),
  2308. diag::err_cast_pointer_from_non_pointer_int)
  2309. << SrcType << SrcExpr.get()->getSourceRange();
  2310. SrcExpr = ExprError();
  2311. return;
  2312. }
  2313. checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
  2314. DestType, Self);
  2315. } else if (!SrcType->isArithmeticType()) {
  2316. if (!DestType->isIntegralType(Self.Context) &&
  2317. DestType->isArithmeticType()) {
  2318. Self.Diag(SrcExpr.get()->getLocStart(),
  2319. diag::err_cast_pointer_to_non_pointer_int)
  2320. << DestType << SrcExpr.get()->getSourceRange();
  2321. SrcExpr = ExprError();
  2322. return;
  2323. }
  2324. }
  2325. if (Self.getLangOpts().OpenCL &&
  2326. !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  2327. if (DestType->isHalfType()) {
  2328. Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
  2329. << DestType << SrcExpr.get()->getSourceRange();
  2330. SrcExpr = ExprError();
  2331. return;
  2332. }
  2333. }
  2334. // ARC imposes extra restrictions on casts.
  2335. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
  2336. checkObjCConversion(Sema::CCK_CStyleCast);
  2337. if (SrcExpr.isInvalid())
  2338. return;
  2339. const PointerType *CastPtr = DestType->getAs<PointerType>();
  2340. if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
  2341. if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
  2342. Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
  2343. Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
  2344. if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
  2345. ExprPtr->getPointeeType()->isObjCLifetimeType() &&
  2346. !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
  2347. Self.Diag(SrcExpr.get()->getLocStart(),
  2348. diag::err_typecheck_incompatible_ownership)
  2349. << SrcType << DestType << Sema::AA_Casting
  2350. << SrcExpr.get()->getSourceRange();
  2351. return;
  2352. }
  2353. }
  2354. }
  2355. else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
  2356. Self.Diag(SrcExpr.get()->getLocStart(),
  2357. diag::err_arc_convesion_of_weak_unavailable)
  2358. << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
  2359. SrcExpr = ExprError();
  2360. return;
  2361. }
  2362. }
  2363. DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
  2364. DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
  2365. DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
  2366. Kind = Self.PrepareScalarCast(SrcExpr, DestType);
  2367. if (SrcExpr.isInvalid())
  2368. return;
  2369. if (Kind == CK_BitCast)
  2370. checkCastAlign();
  2371. }
  2372. /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
  2373. /// const, volatile or both.
  2374. static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
  2375. QualType DestType) {
  2376. if (SrcExpr.isInvalid())
  2377. return;
  2378. QualType SrcType = SrcExpr.get()->getType();
  2379. if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
  2380. DestType->isLValueReferenceType()))
  2381. return;
  2382. QualType TheOffendingSrcType, TheOffendingDestType;
  2383. Qualifiers CastAwayQualifiers;
  2384. if (CastsAwayConstness(Self, SrcType, DestType, true, false,
  2385. &TheOffendingSrcType, &TheOffendingDestType,
  2386. &CastAwayQualifiers) !=
  2387. CastAwayConstnessKind::CACK_Similar)
  2388. return;
  2389. // FIXME: 'restrict' is not properly handled here.
  2390. int qualifiers = -1;
  2391. if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
  2392. qualifiers = 0;
  2393. } else if (CastAwayQualifiers.hasConst()) {
  2394. qualifiers = 1;
  2395. } else if (CastAwayQualifiers.hasVolatile()) {
  2396. qualifiers = 2;
  2397. }
  2398. // This is a variant of int **x; const int **y = (const int **)x;
  2399. if (qualifiers == -1)
  2400. Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2)
  2401. << SrcType << DestType;
  2402. else
  2403. Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual)
  2404. << TheOffendingSrcType << TheOffendingDestType << qualifiers;
  2405. }
  2406. ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
  2407. TypeSourceInfo *CastTypeInfo,
  2408. SourceLocation RPLoc,
  2409. Expr *CastExpr) {
  2410. CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
  2411. Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
  2412. Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
  2413. if (getLangOpts().CPlusPlus) {
  2414. Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
  2415. isa<InitListExpr>(CastExpr));
  2416. } else {
  2417. Op.CheckCStyleCast();
  2418. }
  2419. if (Op.SrcExpr.isInvalid())
  2420. return ExprError();
  2421. // -Wcast-qual
  2422. DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
  2423. return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
  2424. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  2425. &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
  2426. }
  2427. ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
  2428. QualType Type,
  2429. SourceLocation LPLoc,
  2430. Expr *CastExpr,
  2431. SourceLocation RPLoc) {
  2432. assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
  2433. CastOperation Op(*this, Type, CastExpr);
  2434. Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
  2435. Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
  2436. Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
  2437. if (Op.SrcExpr.isInvalid())
  2438. return ExprError();
  2439. auto *SubExpr = Op.SrcExpr.get();
  2440. if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
  2441. SubExpr = BindExpr->getSubExpr();
  2442. if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
  2443. ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
  2444. return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
  2445. Op.ValueKind, CastTypeInfo, Op.Kind,
  2446. Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
  2447. }