SemaCast.cpp 113 KB

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