blob: 57acba3de0bb0f62c52ef1ba2e69003f5bed3b20 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000035 protected:
36
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000038 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000039 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000045 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000046 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000058 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000059
Chris Lattner2c64b7b2007-10-16 21:07:07 +000060 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000061 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000062 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000068 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000070 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000077 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000081
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000082 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000085 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000086 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000105 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
111 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000118
119 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
122 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000123
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
Steve Naroff54055232008-10-27 17:20:55 +0000135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
Steve Naroff4c3580e2008-12-04 23:50:32 +0000137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000141
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
Steve Naroffb619d952008-12-09 12:56:34 +0000147 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000148 class DisableReplaceStmtScope {
149 RewriteObjC &R;
150 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000151
John McCall4b9c2d22011-11-06 09:01:30 +0000152 public:
153 DisableReplaceStmtScope(RewriteObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000161 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner77cd2a02007-10-11 00:43:27 +0000163 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
168 if (isa<ObjCClassDecl>((*I))) {
169 RewriteForwardClassDecl(D);
170 break;
171 }
Chris Lattner682bf922009-03-29 16:50:03 +0000172 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000173 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000174 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000175 }
176 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000177 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000178 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000179 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000180 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000181
182 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000184 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000186 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000187 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Steve Naroff4c3580e2008-12-04 23:50:32 +0000189 if (ReplacingStmt)
190 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000191
Steve Naroffb619d952008-12-09 12:56:34 +0000192 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000193 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000194
Steve Naroff4c3580e2008-12-04 23:50:32 +0000195 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000196 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000197 ReplacedNodes[Old] = New;
198 return;
199 }
200 if (SilenceRewriteMacroWarning)
201 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000202 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
203 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000204 }
Steve Naroffb619d952008-12-09 12:56:34 +0000205
206 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000207 if (DisableReplaceStmt)
208 return;
209
Nick Lewycky7e749242010-10-31 21:07:24 +0000210 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000211 int Size = Rewrite.getRangeSize(SrcRange);
212 if (Size == -1) {
213 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
214 << Old->getSourceRange();
215 return;
216 }
217 // Get the new text.
218 std::string SStr;
219 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000220 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000221 const std::string &Str = S.str();
222
223 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000224 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000225 ReplacedNodes[Old] = New;
226 return;
227 }
228 if (SilenceRewriteMacroWarning)
229 return;
230 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
231 << Old->getSourceRange();
232 }
233
Chris Lattner5f9e2722011-07-23 10:55:15 +0000234 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000235 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000237 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000238 SilenceRewriteMacroWarning)
239 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000241 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
242 }
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000245 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000246 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000247 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000248 SilenceRewriteMacroWarning)
249 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattneraadaf782008-01-31 19:51:04 +0000251 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
252 }
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattnerf04da132007-10-24 17:06:59 +0000254 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000255 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000256 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000257 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000258 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
259 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
260 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000261 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000262 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
263 ObjCImplementationDecl *IMD,
264 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000266 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000267 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
268 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000269 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
270 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000271 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000272 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000273 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
274 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
275 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
276 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000277 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000278 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000279 void RewriteBlockPointerType(std::string& Str, QualType Type);
280 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000281 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000282 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000283 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000284 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000285
Chris Lattnerf04da132007-10-24 17:06:59 +0000286 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000287 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000288 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000289 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
290 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000291 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000292 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000293 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000294 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000295 void RewriteTryReturnStmts(Stmt *S);
296 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000297 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000298 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000299 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000300 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
301 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000302 Stmt *RewriteBreakStmt(BreakStmt *S);
303 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000304 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000305
Steve Naroff54055232008-10-27 17:20:55 +0000306 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000307 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000308
Mike Stump1eb44332009-09-09 15:08:12 +0000309 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000310 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000311 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000312 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000313 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000314 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000315
316 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
317 std::string &Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000318
319 virtual void Initialize(ASTContext &context) = 0;
320
321 // Metadata Rewriting.
322 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
323 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
324 StringRef prefix,
325 StringRef ClassName,
326 std::string &Result) = 0;
327 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
328 std::string &Result) = 0;
329 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
330 StringRef prefix,
331 StringRef ClassName,
332 std::string &Result) = 0;
333 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
334 std::string &Result) = 0;
335
336 // Rewriting ivar access
337 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
338 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
339 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000340
341 // Misc. AST transformation routines. Somtimes they end up calling
342 // rewriting routines on the new ASTs.
343 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
344 Expr **args, unsigned nargs,
345 SourceLocation StartLoc=SourceLocation(),
346 SourceLocation EndLoc=SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Fariborz Jahanian58457172011-12-05 18:43:13 +0000348 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
349 SourceLocation StartLoc=SourceLocation(),
350 SourceLocation EndLoc=SourceLocation());
351
352 void SynthCountByEnumWithState(std::string &buf);
353 void SynthMsgSendFunctionDecl();
354 void SynthMsgSendSuperFunctionDecl();
355 void SynthMsgSendStretFunctionDecl();
356 void SynthMsgSendFpretFunctionDecl();
357 void SynthMsgSendSuperStretFunctionDecl();
358 void SynthGetClassFunctionDecl();
359 void SynthGetMetaClassFunctionDecl();
360 void SynthGetSuperClassFunctionDecl();
361 void SynthSelGetUidFunctionDecl();
362 void SynthSuperContructorFunctionDecl();
363
364 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000365 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000366 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000368 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000369 std::string SynthesizeBlockImpl(BlockExpr *CE,
370 std::string Tag, std::string Desc);
371 std::string SynthesizeBlockDescriptor(std::string DescTag,
372 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000373 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000374 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000375 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000376 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000377 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000378 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
379 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
380 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Fariborz Jahanian58457172011-12-05 18:43:13 +0000382 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000383 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000384 void WarnAboutReturnGotoStmts(Stmt *S);
385 void HasReturnStmts(Stmt *S, bool &hasReturns);
386 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
387 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
388 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
389
390 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000391 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000392 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000393 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000394 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000395 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Steve Naroff54055232008-10-27 17:20:55 +0000397 // We avoid calling Type::isBlockPointerType(), since it operates on the
398 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000399 bool isTopLevelBlockPointerType(QualType T) {
400 return isa<BlockPointerType>(T);
401 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000403 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
404 /// to a function pointer type and upon success, returns true; false
405 /// otherwise.
406 bool convertBlockPointerToFunctionPointer(QualType &T) {
407 if (isTopLevelBlockPointerType(T)) {
408 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
409 T = Context->getPointerType(BPT->getPointeeType());
410 return true;
411 }
412 return false;
413 }
414
Fariborz Jahanian58457172011-12-05 18:43:13 +0000415 bool needToScanForQualifiers(QualType T);
416 QualType getSuperStructType();
417 QualType getConstantStringStructType();
418 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
419 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
420
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000421 void convertToUnqualifiedObjCType(QualType &T) {
422 if (T->isObjCQualifiedIdType())
423 T = Context->getObjCIdType();
424 else if (T->isObjCQualifiedClassType())
425 T = Context->getObjCClassType();
426 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000427 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
428 if (const ObjCObjectPointerType * OBJPT =
429 T->getAsObjCInterfacePointerType()) {
430 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
431 T = QualType(IFaceT, 0);
432 T = Context->getPointerType(T);
433 }
434 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000435 }
436
Steve Naroff54055232008-10-27 17:20:55 +0000437 // FIXME: This predicate seems like it would be useful to add to ASTContext.
438 bool isObjCType(QualType T) {
439 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
440 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Steve Naroff54055232008-10-27 17:20:55 +0000442 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Steve Naroff54055232008-10-27 17:20:55 +0000444 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
445 OCT == Context->getCanonicalType(Context->getObjCClassType()))
446 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Ted Kremenek6217b802009-07-29 21:53:49 +0000448 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000449 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000450 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000451 return true;
452 }
453 return false;
454 }
455 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000456 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000457 void GetExtentOfArgList(const char *Name, const char *&LParen,
458 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000459
Steve Naroff621edce2009-04-29 16:37:50 +0000460 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000461 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000462 if (From[i] == '"')
463 To += "\\\"";
464 else
465 To += From[i];
466 }
467 }
John McCalle23cf432010-12-14 08:05:40 +0000468
469 QualType getSimpleFunctionType(QualType result,
470 const QualType *args,
471 unsigned numArgs,
472 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000473 if (result == Context->getObjCInstanceType())
474 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000475 FunctionProtoType::ExtProtoInfo fpi;
476 fpi.Variadic = variadic;
477 return Context->getFunctionType(result, args, numArgs, fpi);
478 }
John McCall9d125032010-01-15 18:39:57 +0000479
Fariborz Jahanian58457172011-12-05 18:43:13 +0000480 // Helper function: create a CStyleCastExpr with trivial type source info.
481 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
482 CastKind Kind, Expr *E) {
483 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
484 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
485 SourceLocation(), SourceLocation());
486 }
487 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000488
489 class RewriteObjCFragileABI : public RewriteObjC {
490 public:
491
492 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
493 DiagnosticsEngine &D, const LangOptions &LOpts,
494 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
495 D, LOpts,
496 silenceMacroWarn) {}
497
498 ~RewriteObjCFragileABI() {}
499 virtual void Initialize(ASTContext &context);
500
501 // Rewriting metadata
502 template<typename MethodIterator>
503 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
504 MethodIterator MethodEnd,
505 bool IsInstanceMethod,
506 StringRef prefix,
507 StringRef ClassName,
508 std::string &Result);
509 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
510 StringRef prefix,
511 StringRef ClassName,
512 std::string &Result);
513 virtual void RewriteObjCProtocolListMetaData(
514 const ObjCList<ObjCProtocolDecl> &Prots,
515 StringRef prefix, StringRef ClassName, std::string &Result);
516 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
517 std::string &Result);
518 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
519 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
520 std::string &Result);
521
522 // Rewriting ivar
523 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
524 std::string &Result);
525 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
526 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000527}
528
Mike Stump1eb44332009-09-09 15:08:12 +0000529void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
530 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000531 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000532 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000533 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000534 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000535 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000536 // All the args are checked/rewritten. Don't call twice!
537 RewriteBlockPointerDecl(D);
538 break;
539 }
540 }
541}
542
543void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000544 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000545 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000546 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000547}
548
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000549static bool IsHeaderFile(const std::string &Filename) {
550 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000552 if (DotPos == std::string::npos) {
553 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000554 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000557 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
558 // C header: .h
559 // C++ header: .hh or .H;
560 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000561}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000562
Chris Lattner5f9e2722011-07-23 10:55:15 +0000563RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000564 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000565 bool silenceMacroWarn)
566 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
567 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000568 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000569 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000570 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000571 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
572 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000573 "rewriter doesn't support user-specified control flow semantics "
574 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000575}
576
Eli Friedmanbce831b2009-05-18 22:29:17 +0000577ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000578 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000579 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000580 const LangOptions &LOpts,
581 bool SilenceRewriteMacroWarning) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000582 if (true /*!LOpts.ObjCNonFragileABI*/)
583 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
584 else {
585 assert(false && "objective-C rewriter for nonfragile ABI = NYI");
586 return 0;
587 }
Chris Lattnere365c502007-11-30 22:25:36 +0000588}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000589
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000590void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000591 Context = &context;
592 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000593 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000594 MsgSendFunctionDecl = 0;
595 MsgSendSuperFunctionDecl = 0;
596 MsgSendStretFunctionDecl = 0;
597 MsgSendSuperStretFunctionDecl = 0;
598 MsgSendFpretFunctionDecl = 0;
599 GetClassFunctionDecl = 0;
600 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000601 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000602 SelGetUidFunctionDecl = 0;
603 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000604 ConstantStringClassReference = 0;
605 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000606 CurMethodDef = 0;
607 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000608 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000609 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000610 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000611 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000612 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000613 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000614 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000615 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000616 PropParentMap = 0;
617 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000618 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000619 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000621 // Get the ID and start/end of the main file.
622 MainFileID = SM->getMainFileID();
623 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
624 MainFileStart = MainBuf->getBufferStart();
625 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Chris Lattner2c78b872009-04-14 23:22:57 +0000627 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000628}
629
Chris Lattnerf04da132007-10-24 17:06:59 +0000630//===----------------------------------------------------------------------===//
631// Top Level Driver Code
632//===----------------------------------------------------------------------===//
633
Chris Lattner682bf922009-03-29 16:50:03 +0000634void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000635 if (Diags.hasErrorOccurred())
636 return;
637
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000638 // Two cases: either the decl could be in the main file, or it could be in a
639 // #included file. If the former, rewrite it now. If the later, check to see
640 // if we rewrote the #include/#import.
641 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000642 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000644 // If this is for a builtin, ignore it.
645 if (Loc.isInvalid()) return;
646
Steve Naroffebf2b562007-10-23 23:50:29 +0000647 // Look for built-in declarations that we need to refer during the rewrite.
648 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000649 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000650 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000651 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000652 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000653 ConstantStringClassReference = FVD;
654 return;
655 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000656 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
657 if (ID->isThisDeclarationADefinition())
658 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000659 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000660 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000661 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000662 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000663 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000664 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000665 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000666 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
667 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000668 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
669 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000670 DI != DIEnd; ) {
671 if (isa<ObjCClassDecl>((*DI))) {
672 SmallVector<Decl *, 8> DG;
673 Decl *D = (*DI);
674 SourceLocation Loc = D->getLocation();
675 while (DI != DIEnd &&
676 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
Douglas Gregor7723fec2011-12-15 20:29:51 +0000677 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000678 DG.push_back(D);
679 ++DI;
680 D = (*DI);
Douglas Gregor7723fec2011-12-15 20:29:51 +0000681
682 // Following the ObjCClassDecl, we should have the corresponding
683 // ObjCInterfaceDecl. Skip over it.
684 if (DI != DIEnd && isa<ObjCInterfaceDecl>(D) &&
685 Class->getForwardInterfaceDecl() == D) {
686 ++DI;
687 D = (*DI);
688 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000689 }
690 RewriteForwardClassDecl(DG);
691 continue;
692 }
Chris Lattner682bf922009-03-29 16:50:03 +0000693 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000694 ++DI;
695 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000696 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000697 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000698 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000699 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000700}
701
Chris Lattnerf04da132007-10-24 17:06:59 +0000702//===----------------------------------------------------------------------===//
703// Syntactic (non-AST) Rewriting Code
704//===----------------------------------------------------------------------===//
705
Steve Naroffb29b4272008-04-14 22:03:09 +0000706void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000707 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000708 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000709 const char *MainBufStart = MainBuf.begin();
710 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000711 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000713 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000714 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
715 if (*BufPtr == '#') {
716 if (++BufPtr == MainBufEnd)
717 return;
718 while (*BufPtr == ' ' || *BufPtr == '\t')
719 if (++BufPtr == MainBufEnd)
720 return;
721 if (!strncmp(BufPtr, "import", ImportLen)) {
722 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000723 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000724 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000725 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000726 BufPtr += ImportLen;
727 }
728 }
729 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000730}
731
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000732static std::string getIvarAccessString(ObjCIvarDecl *OID) {
733 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000734 std::string S;
735 S = "((struct ";
736 S += ClassDecl->getIdentifier()->getName();
737 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000738 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000739 return S;
740}
741
Steve Naroffa0876e82008-12-02 17:36:43 +0000742void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
743 ObjCImplementationDecl *IMD,
744 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000745 static bool objcGetPropertyDefined = false;
746 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000747 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000748 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000749 const char *startBuf = SM->getCharacterData(startLoc);
750 assert((*startBuf == '@') && "bogus @synthesize location");
751 const char *semiBuf = strchr(startBuf, ';');
752 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000753 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000754 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000755
756 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
757 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000761 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000763 if (!OID)
764 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000765 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000766 if (!PD->getGetterMethodDecl()->isDefined()) {
767 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
768 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
769 ObjCPropertyDecl::OBJC_PR_copy));
770 std::string Getr;
771 if (GenGetProperty && !objcGetPropertyDefined) {
772 objcGetPropertyDefined = true;
773 // FIXME. Is this attribute correct in all cases?
774 Getr = "\nextern \"C\" __declspec(dllimport) "
775 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000776 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000777 RewriteObjCMethodDecl(OID->getContainingInterface(),
778 PD->getGetterMethodDecl(), Getr);
779 Getr += "{ ";
780 // Synthesize an explicit cast to gain access to the ivar.
781 // See objc-act.c:objc_synthesize_new_getter() for details.
782 if (GenGetProperty) {
783 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
784 Getr += "typedef ";
785 const FunctionType *FPRetType = 0;
786 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
787 FPRetType);
788 Getr += " _TYPE";
789 if (FPRetType) {
790 Getr += ")"; // close the precedence "scope" for "*".
791
792 // Now, emit the argument types (if any).
793 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
794 Getr += "(";
795 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
796 if (i) Getr += ", ";
797 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000798 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000799 Getr += ParamStr;
800 }
801 if (FT->isVariadic()) {
802 if (FT->getNumArgs()) Getr += ", ";
803 Getr += "...";
804 }
805 Getr += ")";
806 } else
807 Getr += "()";
808 }
809 Getr += ";\n";
810 Getr += "return (_TYPE)";
811 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000812 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000813 Getr += ", 1)";
814 }
815 else
816 Getr += "return " + getIvarAccessString(OID);
817 Getr += "; }";
818 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000819 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000820
821 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000822 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Steve Naroffeb0646c2008-12-02 15:48:25 +0000824 // Generate the 'setter' function.
825 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000826 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
827 ObjCPropertyDecl::OBJC_PR_copy);
828 if (GenSetProperty && !objcSetPropertyDefined) {
829 objcSetPropertyDefined = true;
830 // FIXME. Is this attribute correct in all cases?
831 Setr = "\nextern \"C\" __declspec(dllimport) "
832 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
833 }
834
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000835 RewriteObjCMethodDecl(OID->getContainingInterface(),
836 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000837 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000838 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000839 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000840 if (GenSetProperty) {
841 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000842 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000843 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000844 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000845 Setr += ", ";
846 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
847 Setr += "0, ";
848 else
849 Setr += "1, ";
850 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
851 Setr += "1)";
852 else
853 Setr += "0)";
854 }
855 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000856 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000857 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000858 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000859 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000860 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000861}
Chris Lattner8a12c272007-10-11 18:38:32 +0000862
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000863static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
864 std::string &typedefString) {
865 typedefString += "#ifndef _REWRITER_typedef_";
866 typedefString += ForwardDecl->getNameAsString();
867 typedefString += "\n";
868 typedefString += "#define _REWRITER_typedef_";
869 typedefString += ForwardDecl->getNameAsString();
870 typedefString += "\n";
871 typedefString += "typedef struct objc_object ";
872 typedefString += ForwardDecl->getNameAsString();
873 typedefString += ";\n#endif\n";
874}
875
876void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
877 const std::string &typedefString) {
878 SourceLocation startLoc = ClassDecl->getLocation();
879 const char *startBuf = SM->getCharacterData(startLoc);
880 const char *semiPtr = strchr(startBuf, ';');
881 // Replace the @class with typedefs corresponding to the classes.
882 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
883}
884
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000885void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000886 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000887 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
888 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
889 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
890 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000891 // Translate to typedef's that forward reference structs with the same name
892 // as the class. As a convenience, we include the original declaration
893 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000894 typedefString += "// @class ";
895 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000896 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000897 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000898 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000899 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000900 DeclGroupRef::iterator I = D.begin();
901 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
902}
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000904void RewriteObjC::RewriteForwardClassDecl(
905 const llvm::SmallVector<Decl*, 8> &D) {
906 std::string typedefString;
907 for (unsigned i = 0; i < D.size(); i++) {
908 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
909 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
910 if (i == 0) {
911 typedefString += "// @class ";
912 typedefString += ForwardDecl->getNameAsString();
913 typedefString += ";\n";
914 }
915 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
916 }
917 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000918}
919
Steve Naroffb29b4272008-04-14 22:03:09 +0000920void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000921 // When method is a synthesized one, such as a getter/setter there is
922 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000923 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000924 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000925 SourceLocation LocStart = Method->getLocStart();
926 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Chandler Carruth64211622011-07-25 21:09:52 +0000928 if (SM->getExpansionLineNumber(LocEnd) >
929 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000930 InsertText(LocStart, "#if 0\n");
931 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000932 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000933 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000934 }
935}
936
Mike Stump1eb44332009-09-09 15:08:12 +0000937void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000938 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Benjamin Kramerd999b372010-02-14 14:14:16 +0000940 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000941 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000942}
943
Steve Naroffb29b4272008-04-14 22:03:09 +0000944void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000945 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Steve Naroff423cb562007-10-30 13:30:57 +0000947 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000948 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000950 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
951 E = CatDecl->prop_end(); I != E; ++I)
952 RewriteProperty(*I);
953
Mike Stump1eb44332009-09-09 15:08:12 +0000954 for (ObjCCategoryDecl::instmeth_iterator
955 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000956 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000957 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000958 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000959 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000960 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000961 RewriteMethodDeclaration(*I);
962
Steve Naroff423cb562007-10-30 13:30:57 +0000963 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000964 ReplaceText(CatDecl->getAtEndRange().getBegin(),
965 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000966}
967
Steve Naroffb29b4272008-04-14 22:03:09 +0000968void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000969 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Steve Naroff752d6ef2007-10-30 16:42:30 +0000971 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000972 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000973
974 for (ObjCProtocolDecl::instmeth_iterator
975 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000976 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000977 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000978 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000979 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000980 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000981 RewriteMethodDeclaration(*I);
982
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000983 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
984 E = PDecl->prop_end(); I != E; ++I)
985 RewriteProperty(*I);
986
Steve Naroff752d6ef2007-10-30 16:42:30 +0000987 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000988 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000989 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000990
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000991 // Must comment out @optional/@required
992 const char *startBuf = SM->getCharacterData(LocStart);
993 const char *endBuf = SM->getCharacterData(LocEnd);
994 for (const char *p = startBuf; p < endBuf; p++) {
995 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000996 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000997 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000999 }
1000 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001001 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001002 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001004 }
1005 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001006}
1007
Steve Naroffb29b4272008-04-14 22:03:09 +00001008void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001009 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001010 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001011 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001012 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001013 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001014}
1015
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001016void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1017 const FunctionType *&FPRetType) {
1018 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001019 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001020 else if (T->isFunctionPointerType() ||
1021 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001022 // needs special handling, since pointer-to-functions have special
1023 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001024 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001025 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001026 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001027 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001028 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001029 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001030 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001031 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001032 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001033 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001034 }
1035 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001036 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001037}
1038
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001039void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1040 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001041 std::string &ResultStr) {
1042 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1043 const FunctionType *FPRetType = 0;
1044 ResultStr += "\nstatic ";
1045 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001046 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001048 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001049 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001051 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001052 NameStr += "_I_";
1053 else
1054 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001056 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001057 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001058
1059 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001060 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001061 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001062 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001063 }
Mike Stump1eb44332009-09-09 15:08:12 +00001064 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001065 {
1066 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001067 int len = selString.size();
1068 for (int i = 0; i < len; i++)
1069 if (selString[i] == ':')
1070 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001071 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001072 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001073 // Remember this name for metadata emission
1074 MethodInternalNames[OMD] = NameStr;
1075 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001077 // Rewrite arguments
1078 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001081 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001082 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001084 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001085 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001086 ResultStr += "struct ";
1087 }
1088 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001089 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001090 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001091 }
1092 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001093 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001094 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001096 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001097 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001101 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1102 E = OMD->param_end(); PI != E; ++PI) {
1103 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001104 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001105 if (PDecl->getType()->isObjCQualifiedIdType()) {
1106 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001107 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001108 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001109 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001110 QualType QT = PDecl->getType();
1111 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1112 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001113 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001114 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001115 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001116 ResultStr += Name;
1117 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001118 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001119 if (OMD->isVariadic())
1120 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001121 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Steve Naroff76e429d2008-07-16 14:40:40 +00001123 if (FPRetType) {
1124 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Steve Naroff76e429d2008-07-16 14:40:40 +00001126 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001127 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001128 ResultStr += "(";
1129 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1130 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001131 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001132 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001133 ResultStr += ParamStr;
1134 }
1135 if (FT->isVariadic()) {
1136 if (FT->getNumArgs()) ResultStr += ", ";
1137 ResultStr += "...";
1138 }
1139 ResultStr += ")";
1140 } else {
1141 ResultStr += "()";
1142 }
1143 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001144}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001145void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001146 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1147 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001149 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001151 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001152 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1153 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001154 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001155 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001156 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001157 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001158 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001159 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001160
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001161 const char *startBuf = SM->getCharacterData(LocStart);
1162 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001163 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001164 }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001166 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001167 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1168 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001169 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001171 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001172 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001173 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001174 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176 const char *startBuf = SM->getCharacterData(LocStart);
1177 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001178 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001179 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001180 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001181 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001182 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001183 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001184 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001185 }
1186
Benjamin Kramerd999b372010-02-14 14:14:16 +00001187 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001188}
1189
Steve Naroffb29b4272008-04-14 22:03:09 +00001190void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001191 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001192 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001193 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001194 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001195 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001196 ResultStr += "\n";
1197 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001198 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001199 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001200 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001201 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001202 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001203 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001204 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001205 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001206 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
1208 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001209 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001210 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001211 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001212 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001213 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001214 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001215 for (ObjCInterfaceDecl::classmeth_iterator
1216 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001217 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001218 RewriteMethodDeclaration(*I);
1219
Steve Naroff2feac5e2007-10-30 03:43:13 +00001220 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001221 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1222 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001223}
1224
John McCall4b9c2d22011-11-06 09:01:30 +00001225Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1226 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001227
John McCall4b9c2d22011-11-06 09:01:30 +00001228 // We just magically know some things about the structure of this
1229 // expression.
1230 ObjCMessageExpr *OldMsg =
1231 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1232 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001233
John McCall4b9c2d22011-11-06 09:01:30 +00001234 // Because the rewriter doesn't allow us to rewrite rewritten code,
1235 // we need to suppress rewriting the sub-statements.
1236 Expr *Base, *RHS;
1237 {
1238 DisableReplaceStmtScope S(*this);
1239
1240 // Rebuild the base expression if we have one.
1241 Base = 0;
1242 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1243 Base = OldMsg->getInstanceReceiver();
1244 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1245 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1246 }
1247
1248 // Rebuild the RHS.
1249 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1250 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1251 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1252 }
1253
1254 // TODO: avoid this copy.
1255 SmallVector<SourceLocation, 1> SelLocs;
1256 OldMsg->getSelectorLocs(SelLocs);
1257
1258 ObjCMessageExpr *NewMsg;
1259 switch (OldMsg->getReceiverKind()) {
1260 case ObjCMessageExpr::Class:
1261 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1262 OldMsg->getValueKind(),
1263 OldMsg->getLeftLoc(),
1264 OldMsg->getClassReceiverTypeInfo(),
1265 OldMsg->getSelector(),
1266 SelLocs,
1267 OldMsg->getMethodDecl(),
1268 RHS,
1269 OldMsg->getRightLoc());
1270 break;
1271
1272 case ObjCMessageExpr::Instance:
1273 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1274 OldMsg->getValueKind(),
1275 OldMsg->getLeftLoc(),
1276 Base,
1277 OldMsg->getSelector(),
1278 SelLocs,
1279 OldMsg->getMethodDecl(),
1280 RHS,
1281 OldMsg->getRightLoc());
1282 break;
1283
1284 case ObjCMessageExpr::SuperClass:
1285 case ObjCMessageExpr::SuperInstance:
1286 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1287 OldMsg->getValueKind(),
1288 OldMsg->getLeftLoc(),
1289 OldMsg->getSuperLoc(),
1290 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1291 OldMsg->getSuperType(),
1292 OldMsg->getSelector(),
1293 SelLocs,
1294 OldMsg->getMethodDecl(),
1295 RHS,
1296 OldMsg->getRightLoc());
1297 break;
1298 }
1299
1300 Stmt *Replacement = SynthMessageExpr(NewMsg);
1301 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1302 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001303}
1304
John McCall4b9c2d22011-11-06 09:01:30 +00001305Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1306 SourceRange OldRange = PseudoOp->getSourceRange();
1307
1308 // We just magically know some things about the structure of this
1309 // expression.
1310 ObjCMessageExpr *OldMsg =
1311 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1312
1313 // Because the rewriter doesn't allow us to rewrite rewritten code,
1314 // we need to suppress rewriting the sub-statements.
1315 Expr *Base = 0;
1316 {
1317 DisableReplaceStmtScope S(*this);
1318
1319 // Rebuild the base expression if we have one.
1320 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1321 Base = OldMsg->getInstanceReceiver();
1322 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1323 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001324 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001325 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001326
John McCall4b9c2d22011-11-06 09:01:30 +00001327 // Intentionally empty.
1328 SmallVector<SourceLocation, 1> SelLocs;
1329 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001330
John McCall4b9c2d22011-11-06 09:01:30 +00001331 ObjCMessageExpr *NewMsg;
1332 switch (OldMsg->getReceiverKind()) {
1333 case ObjCMessageExpr::Class:
1334 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1335 OldMsg->getValueKind(),
1336 OldMsg->getLeftLoc(),
1337 OldMsg->getClassReceiverTypeInfo(),
1338 OldMsg->getSelector(),
1339 SelLocs,
1340 OldMsg->getMethodDecl(),
1341 Args,
1342 OldMsg->getRightLoc());
1343 break;
1344
1345 case ObjCMessageExpr::Instance:
1346 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1347 OldMsg->getValueKind(),
1348 OldMsg->getLeftLoc(),
1349 Base,
1350 OldMsg->getSelector(),
1351 SelLocs,
1352 OldMsg->getMethodDecl(),
1353 Args,
1354 OldMsg->getRightLoc());
1355 break;
1356
1357 case ObjCMessageExpr::SuperClass:
1358 case ObjCMessageExpr::SuperInstance:
1359 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1360 OldMsg->getValueKind(),
1361 OldMsg->getLeftLoc(),
1362 OldMsg->getSuperLoc(),
1363 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1364 OldMsg->getSuperType(),
1365 OldMsg->getSelector(),
1366 SelLocs,
1367 OldMsg->getMethodDecl(),
1368 Args,
1369 OldMsg->getRightLoc());
1370 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001371 }
John McCall4b9c2d22011-11-06 09:01:30 +00001372
1373 Stmt *Replacement = SynthMessageExpr(NewMsg);
1374 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1375 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001376}
1377
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001378/// SynthCountByEnumWithState - To print:
1379/// ((unsigned int (*)
1380/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001381/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001383/// "countByEnumeratingWithState:objects:count:"),
1384/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001385/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001386///
Steve Naroffb29b4272008-04-14 22:03:09 +00001387void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001388 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1389 "id *, unsigned int))(void *)objc_msgSend)";
1390 buf += "\n\t\t";
1391 buf += "((id)l_collection,\n\t\t";
1392 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1393 buf += "\n\t\t";
1394 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001395 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001397
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001398/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1399/// statement to exit to its outer synthesized loop.
1400///
Steve Naroffb29b4272008-04-14 22:03:09 +00001401Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001402 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1403 return S;
1404 // replace break with goto __break_label
1405 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001407 SourceLocation startLoc = S->getLocStart();
1408 buf = "goto __break_label_";
1409 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001410 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001411
1412 return 0;
1413}
1414
1415/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1416/// statement to continue with its inner synthesized loop.
1417///
Steve Naroffb29b4272008-04-14 22:03:09 +00001418Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001419 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1420 return S;
1421 // replace continue with goto __continue_label
1422 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001424 SourceLocation startLoc = S->getLocStart();
1425 buf = "goto __continue_label_";
1426 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001427 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001429 return 0;
1430}
1431
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001432/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001433/// It rewrites:
1434/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001436/// Into:
1437/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001438/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001439/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001440/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001441/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001442/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001443/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001444/// if (limit) {
1445/// unsigned long startMutations = *enumState.mutationsPtr;
1446/// do {
1447/// unsigned long counter = 0;
1448/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001449/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001450/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001451/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001452/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001453/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001454/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001455/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001456/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001457/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001458/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001459/// }
1460/// else
1461/// elem = nil;
1462/// }
1463///
Steve Naroffb29b4272008-04-14 22:03:09 +00001464Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001465 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001466 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001467 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001468 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001469 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001470 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001472 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001473 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001474 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001475 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001476 std::string buf;
1477 buf = "\n{\n\t";
1478 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1479 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001480 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001481 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001482 if (ElementType->isObjCQualifiedIdType() ||
1483 ElementType->isObjCQualifiedInterfaceType())
1484 // Simply use 'id' for all qualified types.
1485 elementTypeAsString = "id";
1486 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001487 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001488 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001489 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001490 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001491 buf += elementName;
1492 buf += ";\n\t";
1493 }
Chris Lattner06767512008-04-08 05:52:18 +00001494 else {
1495 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001496 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001497 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1498 if (VD->getType()->isObjCQualifiedIdType() ||
1499 VD->getType()->isObjCQualifiedInterfaceType())
1500 // Simply use 'id' for all qualified types.
1501 elementTypeAsString = "id";
1502 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001503 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001504 }
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001506 // struct __objcFastEnumerationState enumState = { 0 };
1507 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001508 // id __rw_items[16];
1509 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 // id l_collection = (id)
1511 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001512 // Find start location of 'collection' the hard way!
1513 const char *startCollectionBuf = startBuf;
1514 startCollectionBuf += 3; // skip 'for'
1515 startCollectionBuf = strchr(startCollectionBuf, '(');
1516 startCollectionBuf++; // skip '('
1517 // find 'in' and skip it.
1518 while (*startCollectionBuf != ' ' ||
1519 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1520 (*(startCollectionBuf+3) != ' ' &&
1521 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1522 startCollectionBuf++;
1523 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001524
1525 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001526 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001527 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001528 SourceLocation rightParenLoc = S->getRParenLoc();
1529 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001530 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001531 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001533 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001534 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001535 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001536 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001537 // ((unsigned int (*)
1538 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001539 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001540 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001541 // "countByEnumeratingWithState:objects:count:"),
1542 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001543 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001544 buf += "unsigned long limit =\n\t\t";
1545 SynthCountByEnumWithState(buf);
1546 buf += ";\n\t";
1547 /// if (limit) {
1548 /// unsigned long startMutations = *enumState.mutationsPtr;
1549 /// do {
1550 /// unsigned long counter = 0;
1551 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001552 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001553 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001554 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001555 buf += "if (limit) {\n\t";
1556 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1557 buf += "do {\n\t\t";
1558 buf += "unsigned long counter = 0;\n\t\t";
1559 buf += "do {\n\t\t\t";
1560 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1561 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1562 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001563 buf += " = (";
1564 buf += elementTypeAsString;
1565 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001566 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001567 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001569 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001570 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001571 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001572 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001573 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001574 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001575 /// }
1576 /// else
1577 /// elem = nil;
1578 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001579 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001580 buf = ";\n\t";
1581 buf += "__continue_label_";
1582 buf += utostr(ObjCBcLabelNo.back());
1583 buf += ": ;";
1584 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001585 buf += "} while (counter < limit);\n\t";
1586 buf += "} while (limit = ";
1587 SynthCountByEnumWithState(buf);
1588 buf += ");\n\t";
1589 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001590 buf += " = ((";
1591 buf += elementTypeAsString;
1592 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001593 buf += "__break_label_";
1594 buf += utostr(ObjCBcLabelNo.back());
1595 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001596 buf += "}\n\t";
1597 buf += "else\n\t\t";
1598 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001599 buf += " = ((";
1600 buf += elementTypeAsString;
1601 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001602 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001604 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001605 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001606 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001607 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001608 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001609 } else {
1610 /* Need to treat single statements specially. For example:
1611 *
1612 * for (A *a in b) if (stuff()) break;
1613 * for (A *a in b) xxxyy;
1614 *
1615 * The following code simply scans ahead to the semi to find the actual end.
1616 */
1617 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1618 const char *semiBuf = strchr(stmtBuf, ';');
1619 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001620 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001621 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001622 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001623 Stmts.pop_back();
1624 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001626}
1627
Mike Stump1eb44332009-09-09 15:08:12 +00001628/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001629/// This routine rewrites @synchronized(expr) stmt;
1630/// into:
1631/// objc_sync_enter(expr);
1632/// @try stmt @finally { objc_sync_exit(expr); }
1633///
Steve Naroffb29b4272008-04-14 22:03:09 +00001634Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001635 // Get the start location and compute the semi location.
1636 SourceLocation startLoc = S->getLocStart();
1637 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001639 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001640
1641 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001642 buf = "objc_sync_enter((id)";
1643 const char *lparenBuf = startBuf;
1644 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001645 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001646 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1647 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001648 // been rewritten! (which implies the SourceLocation's are invalid).
1649 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001650 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001651 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001652 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001653 buf = ");\n";
1654 // declare a new scope with two variables, _stack and _rethrow.
1655 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1656 buf += "int buf[18/*32-bit i386*/];\n";
1657 buf += "char *pointers[4];} _stack;\n";
1658 buf += "id volatile _rethrow = 0;\n";
1659 buf += "objc_exception_try_enter(&_stack);\n";
1660 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001661 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001662 startLoc = S->getSynchBody()->getLocEnd();
1663 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Steve Naroffc7089f12008-08-19 13:04:19 +00001665 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001666 SourceLocation lastCurlyLoc = startLoc;
1667 buf = "}\nelse {\n";
1668 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001669 buf += "}\n";
1670 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001671 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001672
1673 std::string syncBuf;
1674 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001675
1676 Expr *syncExpr = S->getSynchExpr();
1677 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1678 ? CK_BitCast :
1679 syncExpr->getType()->isBlockPointerType()
1680 ? CK_BlockPointerToObjCPointerCast
1681 : CK_CPointerToObjCPointerCast;
1682 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1683 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001684 std::string syncExprBufS;
1685 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001686 syncExpr->printPretty(syncExprBuf, *Context, 0,
1687 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001688 syncBuf += syncExprBuf.str();
1689 syncBuf += ");";
1690
1691 buf += syncBuf;
1692 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001693 buf += "}\n";
1694 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Benjamin Kramerd999b372010-02-14 14:14:16 +00001696 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001697
1698 bool hasReturns = false;
1699 HasReturnStmts(S->getSynchBody(), hasReturns);
1700 if (hasReturns)
1701 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1702
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001703 return 0;
1704}
1705
Steve Naroffb85e77a2009-12-05 21:43:12 +00001706void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1707{
Steve Naroff8c565152008-12-05 17:03:39 +00001708 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001709 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001710 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001711 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001712
Steve Naroffb85e77a2009-12-05 21:43:12 +00001713 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001714 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001715 TryFinallyContainsReturnDiag);
1716 }
1717 return;
1718}
1719
Steve Naroffb85e77a2009-12-05 21:43:12 +00001720void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1721{
1722 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001723 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001724 if (*CI)
1725 HasReturnStmts(*CI, hasReturns);
1726
1727 if (isa<ReturnStmt>(S))
1728 hasReturns = true;
1729 return;
1730}
1731
1732void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1733 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001734 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001735 if (*CI) {
1736 RewriteTryReturnStmts(*CI);
1737 }
1738 if (isa<ReturnStmt>(S)) {
1739 SourceLocation startLoc = S->getLocStart();
1740 const char *startBuf = SM->getCharacterData(startLoc);
1741
1742 const char *semiBuf = strchr(startBuf, ';');
1743 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001744 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001745
1746 std::string buf;
1747 buf = "{ objc_exception_try_exit(&_stack); return";
1748
Benjamin Kramerd999b372010-02-14 14:14:16 +00001749 ReplaceText(startLoc, 6, buf);
1750 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001751 }
1752 return;
1753}
1754
1755void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1756 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001757 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001758 if (*CI) {
1759 RewriteSyncReturnStmts(*CI, syncExitBuf);
1760 }
1761 if (isa<ReturnStmt>(S)) {
1762 SourceLocation startLoc = S->getLocStart();
1763 const char *startBuf = SM->getCharacterData(startLoc);
1764
1765 const char *semiBuf = strchr(startBuf, ';');
1766 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001767 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001768
1769 std::string buf;
1770 buf = "{ objc_exception_try_exit(&_stack);";
1771 buf += syncExitBuf;
1772 buf += " return";
1773
Benjamin Kramerd999b372010-02-14 14:14:16 +00001774 ReplaceText(startLoc, 6, buf);
1775 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001776 }
1777 return;
1778}
1779
Steve Naroffb29b4272008-04-14 22:03:09 +00001780Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001781 // Get the start location and compute the semi location.
1782 SourceLocation startLoc = S->getLocStart();
1783 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Steve Naroff75730982007-11-07 04:08:17 +00001785 assert((*startBuf == '@') && "bogus @try location");
1786
1787 std::string buf;
1788 // declare a new scope with two variables, _stack and _rethrow.
1789 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1790 buf += "int buf[18/*32-bit i386*/];\n";
1791 buf += "char *pointers[4];} _stack;\n";
1792 buf += "id volatile _rethrow = 0;\n";
1793 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001794 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001795
Benjamin Kramerd999b372010-02-14 14:14:16 +00001796 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Steve Naroff75730982007-11-07 04:08:17 +00001798 startLoc = S->getTryBody()->getLocEnd();
1799 startBuf = SM->getCharacterData(startLoc);
1800
1801 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Steve Naroff75730982007-11-07 04:08:17 +00001803 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001804 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001805 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001806 buf = " /* @catch begin */ else {\n";
1807 buf += " id _caught = objc_exception_extract(&_stack);\n";
1808 buf += " objc_exception_try_enter (&_stack);\n";
1809 buf += " if (_setjmp(_stack.buf))\n";
1810 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1811 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Benjamin Kramerd999b372010-02-14 14:14:16 +00001813 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001814 } else { /* no catch list */
1815 buf = "}\nelse {\n";
1816 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1817 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001818 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001819 }
Steve Naroff75730982007-11-07 04:08:17 +00001820 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001821 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1822 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001823 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001824
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001825 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001826 buf = "if ("; // we are generating code for the first catch clause
1827 else
1828 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001829 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001830 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Steve Naroff75730982007-11-07 04:08:17 +00001832 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Steve Naroff75730982007-11-07 04:08:17 +00001834 const char *lParenLoc = strchr(startBuf, '(');
1835
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001836 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001837 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001838 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001839 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1840 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001841 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001842 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001843 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Steve Naroffe12e6922008-02-01 20:02:07 +00001845 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001846 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001847 } else if (catchDecl) {
1848 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001849 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001850 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001851 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001852 } else if (const ObjCObjectPointerType *Ptr =
1853 t->getAs<ObjCObjectPointerType>()) {
1854 // Should be a pointer to a class.
1855 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1856 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001857 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001858 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001859 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001860 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001861 }
1862 }
1863 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001864 lastCatchBody = Catch->getCatchBody();
1865 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001866 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1867 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1868 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1869 assert((*rParenBuf == ')') && "bogus @catch paren location");
1870 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Mike Stump1eb44332009-09-09 15:08:12 +00001872 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001873 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001874 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001875 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001876 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001877 }
Steve Naroff75730982007-11-07 04:08:17 +00001878 }
1879 // Complete the catch list...
1880 if (lastCatchBody) {
1881 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001882 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1883 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Steve Naroff378f47a2008-09-11 15:29:03 +00001885 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001886 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001887 buf = "} /* last catch end */\n";
1888 buf += "else {\n";
1889 buf += " _rethrow = _caught;\n";
1890 buf += " objc_exception_try_exit(&_stack);\n";
1891 buf += "} } /* @catch end */\n";
1892 if (!S->getFinallyStmt())
1893 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001894 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Steve Naroff75730982007-11-07 04:08:17 +00001896 // Set lastCurlyLoc
1897 lastCurlyLoc = lastCatchBody->getLocEnd();
1898 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001899 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001900 startLoc = finalStmt->getLocStart();
1901 startBuf = SM->getCharacterData(startLoc);
1902 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Benjamin Kramerd999b372010-02-14 14:14:16 +00001904 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Steve Naroff75730982007-11-07 04:08:17 +00001906 Stmt *body = finalStmt->getFinallyBody();
1907 SourceLocation startLoc = body->getLocStart();
1908 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001909 assert(*SM->getCharacterData(startLoc) == '{' &&
1910 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001911 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001912 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001914 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001915 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001916 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001917 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Steve Naroff75730982007-11-07 04:08:17 +00001919 // Set lastCurlyLoc
1920 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Steve Naroff8c565152008-12-05 17:03:39 +00001922 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001923 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001924 } else { /* no finally clause - make sure we synthesize an implicit one */
1925 buf = "{ /* implicit finally clause */\n";
1926 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1927 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1928 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001929 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001930
1931 // Now check for any return/continue/go statements within the @try.
1932 // The implicit finally clause won't called if the @try contains any
1933 // jump statements.
1934 bool hasReturns = false;
1935 HasReturnStmts(S->getTryBody(), hasReturns);
1936 if (hasReturns)
1937 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001938 }
1939 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001940 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001941 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001942 return 0;
1943}
1944
Mike Stump1eb44332009-09-09 15:08:12 +00001945// This can't be done with ReplaceStmt(S, ThrowExpr), since
1946// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001947// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001948Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001949 // Get the start location and compute the semi location.
1950 SourceLocation startLoc = S->getLocStart();
1951 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Steve Naroff2bd03922007-11-07 15:32:26 +00001953 assert((*startBuf == '@') && "bogus @throw location");
1954
1955 std::string buf;
1956 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001957 if (S->getThrowExpr())
1958 buf = "objc_exception_throw(";
1959 else // add an implicit argument
1960 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001962 // handle "@ throw" correctly.
1963 const char *wBuf = strchr(startBuf, 'w');
1964 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001965 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Steve Naroff2bd03922007-11-07 15:32:26 +00001967 const char *semiBuf = strchr(startBuf, ';');
1968 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001969 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001970 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00001971 return 0;
1972}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001973
Steve Naroffb29b4272008-04-14 22:03:09 +00001974Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001975 // Create a new string expression.
1976 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001977 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001978 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00001979 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00001980 StringLiteral::Ascii, false,
1981 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001982 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Chris Lattner07506182007-11-30 22:53:43 +00001984 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001985 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001986 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001987}
1988
Steve Naroffb29b4272008-04-14 22:03:09 +00001989Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001990 if (!SelGetUidFunctionDecl)
1991 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001992 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1993 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00001994 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00001995 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001996 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00001997 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001998 StringLiteral::Ascii, false,
1999 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002000 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2001 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002002 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002003 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002004 return SelExp;
2005}
2006
Steve Naroffb29b4272008-04-14 22:03:09 +00002007CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002008 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2009 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002010 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002011 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Steve Naroffebf2b562007-10-23 23:50:29 +00002013 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002014 DeclRefExpr *DRE =
2015 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Steve Naroffebf2b562007-10-23 23:50:29 +00002017 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002018 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002019 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002020 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002021 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002022
John McCall183700f2009-09-21 23:43:11 +00002023 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002025 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002026 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002027 FT->getCallResultType(*Context),
2028 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002029 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002030}
2031
Steve Naroffd5255f52007-11-01 13:24:47 +00002032static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2033 const char *&startRef, const char *&endRef) {
2034 while (startBuf < endBuf) {
2035 if (*startBuf == '<')
2036 startRef = startBuf; // mark the start.
2037 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002038 if (startRef && *startRef == '<') {
2039 endRef = startBuf; // mark the end.
2040 return true;
2041 }
2042 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002043 }
2044 startBuf++;
2045 }
2046 return false;
2047}
2048
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002049static void scanToNextArgument(const char *&argRef) {
2050 int angle = 0;
2051 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2052 if (*argRef == '<')
2053 angle++;
2054 else if (*argRef == '>')
2055 angle--;
2056 argRef++;
2057 }
2058 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2059}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002060
Steve Naroffb29b4272008-04-14 22:03:09 +00002061bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002062 if (T->isObjCQualifiedIdType())
2063 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002064 if (const PointerType *PT = T->getAs<PointerType>()) {
2065 if (PT->getPointeeType()->isObjCQualifiedIdType())
2066 return true;
2067 }
2068 if (T->isObjCObjectPointerType()) {
2069 T = T->getPointeeType();
2070 return T->isObjCQualifiedInterfaceType();
2071 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002072 if (T->isArrayType()) {
2073 QualType ElemTy = Context->getBaseElementType(T);
2074 return needToScanForQualifiers(ElemTy);
2075 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002076 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002077}
2078
Steve Naroff4f95b752008-07-29 18:15:38 +00002079void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2080 QualType Type = E->getType();
2081 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002082 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Steve Naroffcda658e2008-11-19 21:15:47 +00002084 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2085 Loc = ECE->getLParenLoc();
2086 EndLoc = ECE->getRParenLoc();
2087 } else {
2088 Loc = E->getLocStart();
2089 EndLoc = E->getLocEnd();
2090 }
2091 // This will defend against trying to rewrite synthesized expressions.
2092 if (Loc.isInvalid() || EndLoc.isInvalid())
2093 return;
2094
Steve Naroff4f95b752008-07-29 18:15:38 +00002095 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002096 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002097 const char *startRef = 0, *endRef = 0;
2098 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2099 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002100 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2101 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002102 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002103 InsertText(LessLoc, "/*");
2104 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002105 }
2106 }
2107}
2108
Steve Naroffb29b4272008-04-14 22:03:09 +00002109void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002110 SourceLocation Loc;
2111 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002112 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002113 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2114 Loc = VD->getLocation();
2115 Type = VD->getType();
2116 }
2117 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2118 Loc = FD->getLocation();
2119 // Check for ObjC 'id' and class types that have been adorned with protocol
2120 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002121 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002122 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002123 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002124 if (!proto)
2125 return;
2126 Type = proto->getResultType();
2127 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002128 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2129 Loc = FD->getLocation();
2130 Type = FD->getType();
2131 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002132 else
2133 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002135 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002136 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Steve Naroffd5255f52007-11-01 13:24:47 +00002138 const char *endBuf = SM->getCharacterData(Loc);
2139 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002140 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002141 startBuf--; // scan backward (from the decl location) for return type.
2142 const char *startRef = 0, *endRef = 0;
2143 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2144 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002145 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2146 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002147 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002148 InsertText(LessLoc, "/*");
2149 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002150 }
2151 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002152 if (!proto)
2153 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002154 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002155 const char *startBuf = SM->getCharacterData(Loc);
2156 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002157 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2158 if (needToScanForQualifiers(proto->getArgType(i))) {
2159 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Steve Naroffd5255f52007-11-01 13:24:47 +00002161 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002162 // scan forward (from the decl location) for argument types.
2163 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002164 const char *startRef = 0, *endRef = 0;
2165 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2166 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002167 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002168 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002169 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002170 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002171 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002172 InsertText(LessLoc, "/*");
2173 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002174 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002175 startBuf = ++endBuf;
2176 }
2177 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002178 // If the function name is derived from a macro expansion, then the
2179 // argument buffer will not follow the name. Need to speak with Chris.
2180 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002181 startBuf++; // scan forward (from the decl location) for argument types.
2182 startBuf++;
2183 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002184 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002185}
2186
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002187void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2188 QualType QT = ND->getType();
2189 const Type* TypePtr = QT->getAs<Type>();
2190 if (!isa<TypeOfExprType>(TypePtr))
2191 return;
2192 while (isa<TypeOfExprType>(TypePtr)) {
2193 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2194 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2195 TypePtr = QT->getAs<Type>();
2196 }
2197 // FIXME. This will not work for multiple declarators; as in:
2198 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002199 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002200 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2201 const char *startBuf = SM->getCharacterData(DeclLoc);
2202 if (ND->getInit()) {
2203 std::string Name(ND->getNameAsString());
2204 TypeAsString += " " + Name + " = ";
2205 Expr *E = ND->getInit();
2206 SourceLocation startLoc;
2207 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2208 startLoc = ECE->getLParenLoc();
2209 else
2210 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002211 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002212 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002213 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002214 }
2215 else {
2216 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002217 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002218 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002219 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002220 }
2221}
2222
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002223// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002224void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002225 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002226 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002227 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002228 QualType getFuncType =
2229 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002230 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002231 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002232 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002233 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002234 SC_Extern,
2235 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002236}
2237
Steve Naroffb29b4272008-04-14 22:03:09 +00002238void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002239 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002240 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002241 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002242 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002243 return;
2244 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002245 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002246}
2247
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002248void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002249 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002250 const char *argPtr = TypeString.c_str();
2251 if (!strchr(argPtr, '^')) {
2252 Str += TypeString;
2253 return;
2254 }
2255 while (*argPtr) {
2256 Str += (*argPtr == '^' ? '*' : *argPtr);
2257 argPtr++;
2258 }
2259}
2260
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002261// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002262void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2263 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002264 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002265 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002266 const char *argPtr = TypeString.c_str();
2267 int paren = 0;
2268 while (*argPtr) {
2269 switch (*argPtr) {
2270 case '(':
2271 Str += *argPtr;
2272 paren++;
2273 break;
2274 case ')':
2275 Str += *argPtr;
2276 paren--;
2277 break;
2278 case '^':
2279 Str += '*';
2280 if (paren == 1)
2281 Str += VD->getNameAsString();
2282 break;
2283 default:
2284 Str += *argPtr;
2285 break;
2286 }
2287 argPtr++;
2288 }
2289}
2290
2291
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002292void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2293 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2294 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2295 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2296 if (!proto)
2297 return;
2298 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002299 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002300 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002301 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002302 FdStr += "(";
2303 unsigned numArgs = proto->getNumArgs();
2304 for (unsigned i = 0; i < numArgs; i++) {
2305 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002306 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002307 if (i+1 < numArgs)
2308 FdStr += ", ";
2309 }
2310 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002311 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002312 CurFunctionDeclToDeclareForBlock = 0;
2313}
2314
Steve Naroffc0a123c2008-03-11 17:37:02 +00002315// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002316void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002317 if (SuperContructorFunctionDecl)
2318 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002319 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002320 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002321 QualType argT = Context->getObjCIdType();
2322 assert(!argT.isNull() && "Can't find 'id' type");
2323 ArgTys.push_back(argT);
2324 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002325 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2326 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002327 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002328 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002329 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002330 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002331 SC_Extern,
2332 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002333}
2334
Steve Naroff09b266e2007-10-30 23:14:51 +00002335// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002336void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002337 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002338 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002339 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002340 assert(!argT.isNull() && "Can't find 'id' type");
2341 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002342 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002343 assert(!argT.isNull() && "Can't find 'SEL' type");
2344 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002345 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2346 &ArgTys[0], ArgTys.size(),
2347 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002348 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002349 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002350 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002351 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002352 SC_Extern,
2353 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002354}
2355
Steve Naroff874e2322007-11-15 10:28:18 +00002356// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002357void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002358 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002359 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002360 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002361 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002362 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002363 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2364 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2365 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002366 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002367 assert(!argT.isNull() && "Can't find 'SEL' type");
2368 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002369 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2370 &ArgTys[0], ArgTys.size(),
2371 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002372 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002373 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002374 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002375 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002376 SC_Extern,
2377 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002378}
2379
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002380// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002381void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002382 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002383 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002384 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002385 assert(!argT.isNull() && "Can't find 'id' type");
2386 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002387 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002388 assert(!argT.isNull() && "Can't find 'SEL' type");
2389 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002390 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002391 &ArgTys[0], ArgTys.size(),
2392 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002393 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002394 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002395 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002396 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002397 SC_Extern,
2398 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002399}
2400
Mike Stump1eb44332009-09-09 15:08:12 +00002401// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002402// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002403void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002404 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002405 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002406 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002407 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002408 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002409 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002410 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2411 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2412 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002413 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002414 assert(!argT.isNull() && "Can't find 'SEL' type");
2415 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002416 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002417 &ArgTys[0], ArgTys.size(),
2418 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002419 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002420 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002421 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002422 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002423 SC_Extern,
2424 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002425}
2426
Steve Naroff1284db82008-05-08 22:02:18 +00002427// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002428void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002429 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002430 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002432 assert(!argT.isNull() && "Can't find 'id' type");
2433 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002434 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002435 assert(!argT.isNull() && "Can't find 'SEL' type");
2436 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002437 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2438 &ArgTys[0], ArgTys.size(),
2439 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002440 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002441 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002442 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002443 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002444 SC_Extern,
2445 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002446}
2447
Steve Naroff09b266e2007-10-30 23:14:51 +00002448// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002449void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002450 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002451 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002452 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002453 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2454 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002455 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002456 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002457 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002458 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002459 SC_Extern,
2460 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002461}
2462
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002463// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2464void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2465 IdentifierInfo *getSuperClassIdent =
2466 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002467 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002468 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002469 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2470 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002471 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002472 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002473 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002474 getSuperClassIdent,
2475 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002476 SC_Extern,
2477 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002478 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002479}
2480
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002481// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002482void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002483 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002484 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002485 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002486 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2487 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002488 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002489 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002490 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002491 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002492 SC_Extern,
2493 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002494}
2495
Steve Naroffb29b4272008-04-14 22:03:09 +00002496Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002497 QualType strType = getConstantStringStructType();
2498
2499 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002500
2501 std::string tmpName = InFileName;
2502 unsigned i;
2503 for (i=0; i < tmpName.length(); i++) {
2504 char c = tmpName.at(i);
2505 // replace any non alphanumeric characters with '_'.
2506 if (!isalpha(c) && (c < '0' || c > '9'))
2507 tmpName[i] = '_';
2508 }
2509 S += tmpName;
2510 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002511 S += utostr(NumObjCStringLiterals++);
2512
Steve Naroffba92b2e2008-03-27 22:29:16 +00002513 Preamble += "static __NSConstantStringImpl " + S;
2514 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2515 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002516 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002517 std::string prettyBufS;
2518 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002519 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2520 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002521 Preamble += prettyBuf.str();
2522 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002523 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002524
2525 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002526 SourceLocation(), &Context->Idents.get(S),
2527 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002528 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2529 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002530 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002531 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002532 VK_RValue, OK_Ordinary,
2533 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002534 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002535 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002536 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002537 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002538 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002539 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002540}
2541
Steve Naroff874e2322007-11-15 10:28:18 +00002542// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002543QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002544 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002545 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002546 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002547 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002548 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002549
Steve Naroff874e2322007-11-15 10:28:18 +00002550 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002551 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002552 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002553 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002554
Steve Naroff874e2322007-11-15 10:28:18 +00002555 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002556 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002557 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002558 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002559 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002560 FieldTypes[i], 0,
2561 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002562 /*Mutable=*/false,
2563 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002564 }
Mike Stump1eb44332009-09-09 15:08:12 +00002565
Douglas Gregor838db382010-02-11 01:19:42 +00002566 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002567 }
2568 return Context->getTagDeclType(SuperStructDecl);
2569}
2570
Steve Naroffb29b4272008-04-14 22:03:09 +00002571QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002572 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002573 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002574 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002575 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002576 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002577
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002578 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002579 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002580 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002581 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002582 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002583 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002584 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002585 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002586
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002587 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002588 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002589 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2590 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002591 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002592 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002593 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002594 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002595 /*Mutable=*/true,
2596 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002597 }
2598
Douglas Gregor838db382010-02-11 01:19:42 +00002599 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002600 }
2601 return Context->getTagDeclType(ConstantStringDecl);
2602}
2603
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002604Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2605 SourceLocation StartLoc,
2606 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002607 if (!SelGetUidFunctionDecl)
2608 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002609 if (!MsgSendFunctionDecl)
2610 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002611 if (!MsgSendSuperFunctionDecl)
2612 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002613 if (!MsgSendStretFunctionDecl)
2614 SynthMsgSendStretFunctionDecl();
2615 if (!MsgSendSuperStretFunctionDecl)
2616 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002617 if (!MsgSendFpretFunctionDecl)
2618 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002619 if (!GetClassFunctionDecl)
2620 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002621 if (!GetSuperClassFunctionDecl)
2622 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002623 if (!GetMetaClassFunctionDecl)
2624 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Steve Naroff874e2322007-11-15 10:28:18 +00002626 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002627 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2628 // May need to use objc_msgSend_stret() as well.
2629 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002630 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2631 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002632 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002633 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002634 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002635 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002636 }
Mike Stump1eb44332009-09-09 15:08:12 +00002637
Steve Naroff934f2762007-10-24 22:48:43 +00002638 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002639 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002640 switch (Exp->getReceiverKind()) {
2641 case ObjCMessageExpr::SuperClass: {
2642 MsgSendFlavor = MsgSendSuperFunctionDecl;
2643 if (MsgSendStretFlavor)
2644 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2645 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Douglas Gregor04badcf2010-04-21 00:45:42 +00002647 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Chris Lattner5f9e2722011-07-23 10:55:15 +00002649 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002650
Douglas Gregor04badcf2010-04-21 00:45:42 +00002651 // set the receiver to self, the first argument to all methods.
2652 InitExprs.push_back(
2653 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002654 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002655 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002656 Context->getObjCIdType(),
2657 VK_RValue,
2658 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002659 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Douglas Gregor04badcf2010-04-21 00:45:42 +00002661 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002662 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002663 QualType argType = Context->getPointerType(Context->CharTy);
2664 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002665 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002666 StringLiteral::Ascii, false,
2667 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002668 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2669 &ClsExprs[0],
2670 ClsExprs.size(),
2671 StartLoc,
2672 EndLoc);
2673 // (Class)objc_getClass("CurrentClass")
2674 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2675 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002676 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002677 ClsExprs.clear();
2678 ClsExprs.push_back(ArgExpr);
2679 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2680 &ClsExprs[0], ClsExprs.size(),
2681 StartLoc, EndLoc);
2682
2683 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2684 // To turn off a warning, type-cast to 'id'
2685 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2686 NoTypeInfoCStyleCastExpr(Context,
2687 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002688 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002689 // struct objc_super
2690 QualType superType = getSuperStructType();
2691 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002692
Francois Pichet62ec1f22011-09-17 17:15:52 +00002693 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002694 SynthSuperContructorFunctionDecl();
2695 // Simulate a contructor call...
2696 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002697 superType, VK_LValue,
2698 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002699 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2700 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002701 superType, VK_LValue,
2702 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002703 // The code for super is a little tricky to prevent collision with
2704 // the structure definition in the header. The rewriter has it's own
2705 // internal definition (__rw_objc_super) that is uses. This is why
2706 // we need the cast below. For example:
2707 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2708 //
John McCall2de56d12010-08-25 11:45:40 +00002709 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002710 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002711 VK_RValue, OK_Ordinary,
2712 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002713 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2714 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002715 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002716 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002717 // (struct objc_super) { <exprs from above> }
2718 InitListExpr *ILE =
2719 new (Context) InitListExpr(*Context, SourceLocation(),
2720 &InitExprs[0], InitExprs.size(),
2721 SourceLocation());
2722 TypeSourceInfo *superTInfo
2723 = Context->getTrivialTypeSourceInfo(superType);
2724 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002725 superType, VK_LValue,
2726 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002727 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002728 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002729 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002730 VK_RValue, OK_Ordinary,
2731 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002732 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002733 MsgExprs.push_back(SuperRep);
2734 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002735 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002736
2737 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002738 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002739 QualType argType = Context->getPointerType(Context->CharTy);
2740 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002741 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002742 IdentifierInfo *clsName = Class->getIdentifier();
2743 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002744 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002745 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002746 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002747 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2748 &ClsExprs[0],
2749 ClsExprs.size(),
2750 StartLoc, EndLoc);
2751 MsgExprs.push_back(Cls);
2752 break;
2753 }
2754
2755 case ObjCMessageExpr::SuperInstance:{
2756 MsgSendFlavor = MsgSendSuperFunctionDecl;
2757 if (MsgSendStretFlavor)
2758 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2759 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2760 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002761 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002762
2763 InitExprs.push_back(
2764 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002765 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002766 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002767 Context->getObjCIdType(),
2768 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002769 ); // set the 'receiver'.
2770
2771 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002772 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002773 QualType argType = Context->getPointerType(Context->CharTy);
2774 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002775 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002776 StringLiteral::Ascii, false, argType,
2777 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002778 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2779 &ClsExprs[0],
2780 ClsExprs.size(),
2781 StartLoc, EndLoc);
2782 // (Class)objc_getClass("CurrentClass")
2783 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2784 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002785 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002786 ClsExprs.clear();
2787 ClsExprs.push_back(ArgExpr);
2788 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2789 &ClsExprs[0], ClsExprs.size(),
2790 StartLoc, EndLoc);
2791
2792 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2793 // To turn off a warning, type-cast to 'id'
2794 InitExprs.push_back(
2795 // set 'super class', using class_getSuperclass().
2796 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002797 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002798 // struct objc_super
2799 QualType superType = getSuperStructType();
2800 Expr *SuperRep;
2801
Francois Pichet62ec1f22011-09-17 17:15:52 +00002802 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002803 SynthSuperContructorFunctionDecl();
2804 // Simulate a contructor call...
2805 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002806 superType, VK_LValue,
2807 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002808 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2809 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002810 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002811 // The code for super is a little tricky to prevent collision with
2812 // the structure definition in the header. The rewriter has it's own
2813 // internal definition (__rw_objc_super) that is uses. This is why
2814 // we need the cast below. For example:
2815 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2816 //
John McCall2de56d12010-08-25 11:45:40 +00002817 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002818 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002819 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002820 SourceLocation());
2821 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2822 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002823 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002824 } else {
2825 // (struct objc_super) { <exprs from above> }
2826 InitListExpr *ILE =
2827 new (Context) InitListExpr(*Context, SourceLocation(),
2828 &InitExprs[0], InitExprs.size(),
2829 SourceLocation());
2830 TypeSourceInfo *superTInfo
2831 = Context->getTrivialTypeSourceInfo(superType);
2832 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002833 superType, VK_RValue, ILE,
2834 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002835 }
2836 MsgExprs.push_back(SuperRep);
2837 break;
2838 }
2839
2840 case ObjCMessageExpr::Instance: {
2841 // Remove all type-casts because it may contain objc-style types; e.g.
2842 // Foo<Proto> *.
2843 Expr *recExpr = Exp->getInstanceReceiver();
2844 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2845 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002846 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2847 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2848 ? CK_BlockPointerToObjCPointerCast
2849 : CK_CPointerToObjCPointerCast;
2850
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002852 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002853 MsgExprs.push_back(recExpr);
2854 break;
2855 }
2856 }
2857
Steve Naroffbeaf2992007-11-03 11:27:19 +00002858 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002859 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002860 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002861 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002862 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002863 StringLiteral::Ascii, false,
2864 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002865 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002866 &SelExprs[0], SelExprs.size(),
2867 StartLoc,
2868 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002869 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Steve Naroff934f2762007-10-24 22:48:43 +00002871 // Now push any user supplied arguments.
2872 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002873 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002874 // Make all implicit casts explicit...ICE comes in handy:-)
2875 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2876 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002877 QualType type = ICE->getType();
2878 if (needToScanForQualifiers(type))
2879 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002880 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002881 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002882 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002883 CastKind CK;
2884 if (SubExpr->getType()->isIntegralType(*Context) &&
2885 type->isBooleanType()) {
2886 CK = CK_IntegralToBoolean;
2887 } else if (type->isObjCObjectPointerType()) {
2888 if (SubExpr->getType()->isBlockPointerType()) {
2889 CK = CK_BlockPointerToObjCPointerCast;
2890 } else if (SubExpr->getType()->isPointerType()) {
2891 CK = CK_CPointerToObjCPointerCast;
2892 } else {
2893 CK = CK_BitCast;
2894 }
2895 } else {
2896 CK = CK_BitCast;
2897 }
2898
2899 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002900 }
2901 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002902 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002903 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002904 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002905 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002906 CastKind CK;
2907 if (userExpr->getType()->isIntegralType(*Context)) {
2908 CK = CK_IntegralToPointer;
2909 } else if (userExpr->getType()->isBlockPointerType()) {
2910 CK = CK_BlockPointerToObjCPointerCast;
2911 } else if (userExpr->getType()->isPointerType()) {
2912 CK = CK_CPointerToObjCPointerCast;
2913 } else {
2914 CK = CK_BitCast;
2915 }
John McCall9d125032010-01-15 18:39:57 +00002916 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002917 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002918 }
Mike Stump1eb44332009-09-09 15:08:12 +00002919 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002920 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002921 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2922 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002923 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002924 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002925 }
Steve Naroffab972d32007-11-04 22:37:50 +00002926 // Generate the funky cast.
2927 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002928 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002929 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Steve Naroffab972d32007-11-04 22:37:50 +00002931 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002932 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2933 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2934 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002935 ArgTypes.push_back(Context->getObjCIdType());
2936 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002937 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002938 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002939 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2940 E = OMD->param_end(); PI != E; ++PI) {
2941 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002942 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002943 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002944 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002945 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002946 ArgTypes.push_back(t);
2947 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002948 returnType = Exp->getType();
2949 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002950 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002951 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002952 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002953 }
2954 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002955 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002956
Steve Naroffab972d32007-11-04 22:37:50 +00002957 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002958 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002959 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002960
Mike Stump1eb44332009-09-09 15:08:12 +00002961 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002962 // If we don't do this cast, we get the following bizarre warning/note:
2963 // xx.m:13: warning: function called through a non-compatible type
2964 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002965 cast = NoTypeInfoCStyleCastExpr(Context,
2966 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002967 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Steve Naroffab972d32007-11-04 22:37:50 +00002969 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00002970 QualType castType =
2971 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2972 // If we don't have a method decl, force a variadic cast.
2973 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002974 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00002975 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00002976 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002977
2978 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002979 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002980
John McCall183700f2009-09-21 23:43:11 +00002981 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002982 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002983 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002984 FT->getResultType(), VK_RValue,
2985 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002986 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002987 if (MsgSendStretFlavor) {
2988 // We have the method which returns a struct/union. Must also generate
2989 // call to objc_msgSend_stret and hang both varieties on a conditional
2990 // expression which dictate which one to envoke depending on size of
2991 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002993 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002994 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002995 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002996 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002997 cast = NoTypeInfoCStyleCastExpr(Context,
2998 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002999 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003000 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003001 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3002 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003003 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003004 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003005 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003007 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003008 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003009
John McCall183700f2009-09-21 23:43:11 +00003010 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003011 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003012 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003013 FT->getResultType(), VK_RValue,
3014 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003015
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003016 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003017 UnaryExprOrTypeTraitExpr *sizeofExpr =
3018 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3019 Context->getTrivialTypeSourceInfo(returnType),
3020 Context->getSizeType(), SourceLocation(),
3021 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003022 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3023 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3024 // For X86 it is more complicated and some kind of target specific routine
3025 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003026 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003027 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003028 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3029 llvm::APInt(IntSize, 8),
3030 Context->IntTy,
3031 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003032 BinaryOperator *lessThanExpr =
3033 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3034 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003035 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003036 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003037 new (Context) ConditionalOperator(lessThanExpr,
3038 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003039 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003040 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003041 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3042 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003043 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003044 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003045 return ReplacingStmt;
3046}
3047
Steve Naroffb29b4272008-04-14 22:03:09 +00003048Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003049 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3050 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003051
Steve Naroff934f2762007-10-24 22:48:43 +00003052 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003053 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003055 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003056 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003057}
3058
Steve Naroff621edce2009-04-29 16:37:50 +00003059// typedef struct objc_object Protocol;
3060QualType RewriteObjC::getProtocolType() {
3061 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003062 TypeSourceInfo *TInfo
3063 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003064 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003065 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003066 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003067 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003068 }
3069 return Context->getTypeDeclType(ProtocolTypeDecl);
3070}
3071
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003072/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003073/// a synthesized/forward data reference (to the protocol's metadata).
3074/// The forward references (and metadata) are generated in
3075/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003076Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003077 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3078 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003079 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003080 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003081 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003082 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3083 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003084 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003085 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003086 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003087 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003088 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003089 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003090 ReplaceStmt(Exp, castExpr);
3091 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003092 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003093 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003095}
3096
Mike Stump1eb44332009-09-09 15:08:12 +00003097bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003098 const char *endBuf) {
3099 while (startBuf < endBuf) {
3100 if (*startBuf == '#') {
3101 // Skip whitespace.
3102 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3103 ;
3104 if (!strncmp(startBuf, "if", strlen("if")) ||
3105 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3106 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3107 !strncmp(startBuf, "define", strlen("define")) ||
3108 !strncmp(startBuf, "undef", strlen("undef")) ||
3109 !strncmp(startBuf, "else", strlen("else")) ||
3110 !strncmp(startBuf, "elif", strlen("elif")) ||
3111 !strncmp(startBuf, "endif", strlen("endif")) ||
3112 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3113 !strncmp(startBuf, "include", strlen("include")) ||
3114 !strncmp(startBuf, "import", strlen("import")) ||
3115 !strncmp(startBuf, "include_next", strlen("include_next")))
3116 return true;
3117 }
3118 startBuf++;
3119 }
3120 return false;
3121}
3122
Fariborz Jahanian58457172011-12-05 18:43:13 +00003123/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003124/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003125void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003126 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003127 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003128 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003129 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003130 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003131 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003132 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003133 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003134 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003135 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003136 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003137
Steve Narofffea763e82007-11-14 19:25:57 +00003138 const char *startBuf = SM->getCharacterData(LocStart);
3139 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003140
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003141 // If no ivars and no root or if its root, directly or indirectly,
3142 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003143 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003144 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003145 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003146 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003147 return;
3148 }
Mike Stump1eb44332009-09-09 15:08:12 +00003149
3150 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003151 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003152 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003153 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003154 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003155 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003156
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003157 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003158 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003159 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003160 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003161 // If the buffer contains preprocessor directives, we do more fine-grained
3162 // rewrites. This is intended to fix code that looks like (which occurs in
3163 // NSURL.h, for example):
3164 //
3165 // #ifdef XYZ
3166 // @interface Foo : NSObject
3167 // #else
3168 // @interface FooBar : NSObject
3169 // #endif
3170 // {
3171 // int i;
3172 // }
3173 // @end
3174 //
3175 // This clause is segregated to avoid breaking the common case.
3176 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003177 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003178 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003179 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003180 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003181
Chris Lattnercafeb352009-02-20 18:18:36 +00003182 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003183 // advance to the end of the referenced protocols.
3184 while (endHeader < cursor && *endHeader != '>') endHeader++;
3185 endHeader++;
3186 }
3187 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003188 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003189 } else {
3190 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003191 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003192 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003193 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003194 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003195 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003196 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003197 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003198 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003199
Steve Narofffea763e82007-11-14 19:25:57 +00003200 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003201 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003202 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003203 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003204 }
3205 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003206
Steve Narofffea763e82007-11-14 19:25:57 +00003207 // Now comment out any visibility specifiers.
3208 while (cursor < endBuf) {
3209 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003210 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003211 // Skip whitespace.
3212 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3213 /*scan*/;
3214
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003215 // FIXME: presence of @public, etc. inside comment results in
3216 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003217 if (!strncmp(cursor, "public", strlen("public")) ||
3218 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003219 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003220 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003221 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003222 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003223 // FIXME: If there are cases where '<' is used in ivar declaration part
3224 // of user code, then scan the ivar list and use needToScanForQualifiers
3225 // for type checking.
3226 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003227 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003228 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003229 cursor = strchr(cursor, '>');
3230 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003231 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003232 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003233 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003234 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003235 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003236 }
Steve Narofffea763e82007-11-14 19:25:57 +00003237 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003238 }
Steve Narofffea763e82007-11-14 19:25:57 +00003239 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003240 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003241 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003242 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003243 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003244 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003245 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003246 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003247 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003248 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003249 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003250 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003251 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003252 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003253}
3254
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003255//===----------------------------------------------------------------------===//
3256// Meta Data Emission
3257//===----------------------------------------------------------------------===//
3258
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003259
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003260/// RewriteImplementations - This routine rewrites all method implementations
3261/// and emits meta-data.
3262
Steve Narofface66252008-11-13 20:07:04 +00003263void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003264 int ClsDefCount = ClassImplementation.size();
3265 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003266
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003267 // Rewrite implemented methods
3268 for (int i = 0; i < ClsDefCount; i++)
3269 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003270
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003271 for (int i = 0; i < CatDefCount; i++)
3272 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003273}
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003275void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3276 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003277 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003278 assert(BlockByRefDeclNo.count(VD) &&
3279 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003280 if (def)
3281 ResultStr += "struct ";
3282 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003283 "_" + utostr(BlockByRefDeclNo[VD]) ;
3284}
3285
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003286static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3287 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3288 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3289 return false;
3290}
3291
Steve Naroff54055232008-10-27 17:20:55 +00003292std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003293 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003294 std::string Tag) {
3295 const FunctionType *AFT = CE->getFunctionType();
3296 QualType RT = AFT->getResultType();
3297 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003298 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003299 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003300
Steve Naroff54055232008-10-27 17:20:55 +00003301 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Douglas Gregor72564e72009-02-26 23:50:07 +00003303 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003304 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003305 // block (to reference imported block decl refs).
3306 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003307 } else if (BD->param_empty()) {
3308 S += "(" + StructRef + " *__cself)";
3309 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003310 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003311 assert(FT && "SynthesizeBlockFunc: No function proto");
3312 S += '(';
3313 // first add the implicit argument.
3314 S += StructRef + " *__cself, ";
3315 std::string ParamStr;
3316 for (BlockDecl::param_iterator AI = BD->param_begin(),
3317 E = BD->param_end(); AI != E; ++AI) {
3318 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003319 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003320 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003321 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00003322 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003323 else
Douglas Gregor30c42402011-09-27 22:38:19 +00003324 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003325 S += ParamStr;
3326 }
3327 if (FT->isVariadic()) {
3328 if (!BD->param_empty()) S += ", ";
3329 S += "...";
3330 }
3331 S += ')';
3332 }
3333 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003334
Steve Naroff54055232008-10-27 17:20:55 +00003335 // Create local declarations to avoid rewriting all closure decl ref exprs.
3336 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003337 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003338 E = BlockByRefDecls.end(); I != E; ++I) {
3339 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003340 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003341 std::string TypeString;
3342 RewriteByRefString(TypeString, Name, (*I));
3343 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003344 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003345 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003346 }
Steve Naroff54055232008-10-27 17:20:55 +00003347 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003348 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003349 E = BlockByCopyDecls.end(); I != E; ++I) {
3350 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003351 // Handle nested closure invocation. For example:
3352 //
3353 // void (^myImportedClosure)(void);
3354 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003355 //
Steve Naroff54055232008-10-27 17:20:55 +00003356 // void (^anotherClosure)(void);
3357 // anotherClosure = ^(void) {
3358 // myImportedClosure(); // import and invoke the closure
3359 // };
3360 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003361 if (isTopLevelBlockPointerType((*I)->getType())) {
3362 RewriteBlockPointerTypeVariable(S, (*I));
3363 S += " = (";
3364 RewriteBlockPointerType(S, (*I)->getType());
3365 S += ")";
3366 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3367 }
3368 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003369 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003370 QualType QT = (*I)->getType();
3371 if (HasLocalVariableExternalStorage(*I))
3372 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003373 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003374 S += Name + " = __cself->" +
3375 (*I)->getNameAsString() + "; // bound by copy\n";
3376 }
Steve Naroff54055232008-10-27 17:20:55 +00003377 }
3378 std::string RewrittenStr = RewrittenBlockExprs[CE];
3379 const char *cstr = RewrittenStr.c_str();
3380 while (*cstr++ != '{') ;
3381 S += cstr;
3382 S += "\n";
3383 return S;
3384}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003385
Steve Naroff54055232008-10-27 17:20:55 +00003386std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003387 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003388 std::string Tag) {
3389 std::string StructRef = "struct " + Tag;
3390 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Steve Naroff54055232008-10-27 17:20:55 +00003392 S += funcName;
3393 S += "_block_copy_" + utostr(i);
3394 S += "(" + StructRef;
3395 S += "*dst, " + StructRef;
3396 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003397 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003398 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003399 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003400 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003401 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003402 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003403 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003404 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003405 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003406 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003407 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003408 else
3409 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003410 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003411 S += "}\n";
3412
Steve Naroff54055232008-10-27 17:20:55 +00003413 S += "\nstatic void __";
3414 S += funcName;
3415 S += "_block_dispose_" + utostr(i);
3416 S += "(" + StructRef;
3417 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003418 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003419 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003420 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003421 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003422 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003423 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003424 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003425 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003426 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003427 else
3428 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003429 }
Mike Stump1eb44332009-09-09 15:08:12 +00003430 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003431 return S;
3432}
3433
Steve Naroff01aec112009-12-06 21:14:13 +00003434std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3435 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003436 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003437 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003438
Steve Naroff54055232008-10-27 17:20:55 +00003439 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003440 S += " struct " + Desc;
3441 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003442
Steve Naroff01aec112009-12-06 21:14:13 +00003443 Constructor += "(void *fp, "; // Invoke function pointer.
3444 Constructor += "struct " + Desc; // Descriptor pointer.
3445 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Steve Naroff54055232008-10-27 17:20:55 +00003447 if (BlockDeclRefs.size()) {
3448 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003449 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003450 E = BlockByCopyDecls.end(); I != E; ++I) {
3451 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003452 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003453 std::string ArgName = "_" + FieldName;
3454 // Handle nested closure invocation. For example:
3455 //
3456 // void (^myImportedBlock)(void);
3457 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003458 //
Steve Naroff54055232008-10-27 17:20:55 +00003459 // void (^anotherBlock)(void);
3460 // anotherBlock = ^(void) {
3461 // myImportedBlock(); // import and invoke the closure
3462 // };
3463 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003464 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003465 S += "struct __block_impl *";
3466 Constructor += ", void *" + ArgName;
3467 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003468 QualType QT = (*I)->getType();
3469 if (HasLocalVariableExternalStorage(*I))
3470 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003471 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3472 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003473 Constructor += ", " + ArgName;
3474 }
3475 S += FieldName + ";\n";
3476 }
3477 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003478 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003479 E = BlockByRefDecls.end(); I != E; ++I) {
3480 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003481 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003482 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003483 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003484 std::string TypeString;
3485 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003486 TypeString += " *";
3487 FieldName = TypeString + FieldName;
3488 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003489 Constructor += ", " + ArgName;
3490 }
3491 S += FieldName + "; // by ref\n";
3492 }
3493 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003494 Constructor += ", int flags=0)";
3495 // Initialize all "by copy" arguments.
3496 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003497 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003498 E = BlockByCopyDecls.end(); I != E; ++I) {
3499 std::string Name = (*I)->getNameAsString();
3500 if (firsTime) {
3501 Constructor += " : ";
3502 firsTime = false;
3503 }
3504 else
3505 Constructor += ", ";
3506 if (isTopLevelBlockPointerType((*I)->getType()))
3507 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3508 else
3509 Constructor += Name + "(_" + Name + ")";
3510 }
3511 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003512 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003513 E = BlockByRefDecls.end(); I != E; ++I) {
3514 std::string Name = (*I)->getNameAsString();
3515 if (firsTime) {
3516 Constructor += " : ";
3517 firsTime = false;
3518 }
3519 else
3520 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003521 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003522 }
3523
3524 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003525 if (GlobalVarDecl)
3526 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3527 else
3528 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003529 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Steve Naroff01aec112009-12-06 21:14:13 +00003531 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003532 } else {
3533 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003534 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003535 if (GlobalVarDecl)
3536 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3537 else
3538 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003539 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3540 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003541 }
3542 Constructor += " ";
3543 Constructor += "}\n";
3544 S += Constructor;
3545 S += "};\n";
3546 return S;
3547}
3548
Steve Naroff01aec112009-12-06 21:14:13 +00003549std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3550 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003551 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003552 unsigned hasCopy) {
3553 std::string S = "\nstatic struct " + DescTag;
3554
3555 S += " {\n unsigned long reserved;\n";
3556 S += " unsigned long Block_size;\n";
3557 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003558 S += " void (*copy)(struct ";
3559 S += ImplTag; S += "*, struct ";
3560 S += ImplTag; S += "*);\n";
3561
3562 S += " void (*dispose)(struct ";
3563 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003564 }
3565 S += "} ";
3566
3567 S += DescTag + "_DATA = { 0, sizeof(struct ";
3568 S += ImplTag + ")";
3569 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003570 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3571 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003572 }
3573 S += "};\n";
3574 return S;
3575}
3576
Steve Naroff54055232008-10-27 17:20:55 +00003577void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003578 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003579 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003580 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003581 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003582 bool RewriteSC = (GlobalVarDecl &&
3583 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003584 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003585 GlobalVarDecl->getType().getCVRQualifiers());
3586 if (RewriteSC) {
3587 std::string SC(" void __");
3588 SC += GlobalVarDecl->getNameAsString();
3589 SC += "() {}";
3590 InsertText(FunLocStart, SC);
3591 }
3592
Steve Naroff54055232008-10-27 17:20:55 +00003593 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003594 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3595 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003596 // Need to copy-in the inner copied-in variables not actually used in this
3597 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003598 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3599 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3600 ValueDecl *VD = Exp->getDecl();
3601 BlockDeclRefs.push_back(Exp);
3602 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3603 BlockByCopyDeclsPtrSet.insert(VD);
3604 BlockByCopyDecls.push_back(VD);
3605 }
3606 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3607 BlockByRefDeclsPtrSet.insert(VD);
3608 BlockByRefDecls.push_back(VD);
3609 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003610 // imported objects in the inner blocks not used in the outer
3611 // blocks must be copied/disposed in the outer block as well.
3612 if (Exp->isByRef() ||
3613 VD->getType()->isObjCObjectPointerType() ||
3614 VD->getType()->isBlockPointerType())
3615 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003616 }
Steve Naroff54055232008-10-27 17:20:55 +00003617
Daniel Dunbar4087f272010-08-17 22:39:59 +00003618 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3619 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Steve Naroff01aec112009-12-06 21:14:13 +00003621 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003622
Benjamin Kramerd999b372010-02-14 14:14:16 +00003623 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003624
Steve Naroff01aec112009-12-06 21:14:13 +00003625 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Benjamin Kramerd999b372010-02-14 14:14:16 +00003627 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003628
3629 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003630 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003631 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003632 }
Steve Naroff01aec112009-12-06 21:14:13 +00003633 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3634 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003635 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003636
Steve Naroff54055232008-10-27 17:20:55 +00003637 BlockDeclRefs.clear();
3638 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003639 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003640 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003641 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003642 ImportedBlockDecls.clear();
3643 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003644 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003645 // Must insert any 'const/volatile/static here. Since it has been
3646 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003647 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003648 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003649 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003650 if (GlobalVarDecl->getType().isConstQualified())
3651 SC += "const ";
3652 if (GlobalVarDecl->getType().isVolatileQualified())
3653 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003654 if (GlobalVarDecl->getType().isRestrictQualified())
3655 SC += "restrict ";
3656 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003657 }
3658
Steve Naroff54055232008-10-27 17:20:55 +00003659 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003660 InnerDeclRefsCount.clear();
3661 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003662 RewrittenBlockExprs.clear();
3663}
3664
3665void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3666 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003667 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Steve Naroff54055232008-10-27 17:20:55 +00003669 SynthesizeBlockLiterals(FunLocStart, FuncName);
3670}
3671
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003672static void BuildUniqueMethodName(std::string &Name,
3673 ObjCMethodDecl *MD) {
3674 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003675 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003676 Name += "__" + MD->getSelector().getAsString();
3677 // Convert colons to underscores.
3678 std::string::size_type loc = 0;
3679 while ((loc = Name.find(":", loc)) != std::string::npos)
3680 Name.replace(loc, 1, "_");
3681}
3682
Steve Naroff54055232008-10-27 17:20:55 +00003683void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003684 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3685 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003686 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003687 std::string FuncName;
3688 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003689 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003690}
3691
3692void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003693 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003694 if (*CI) {
3695 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3696 GetBlockDeclRefExprs(CBE->getBody());
3697 else
3698 GetBlockDeclRefExprs(*CI);
3699 }
3700 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003701 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00003702 // FIXME: Handle enums.
3703 if (!isa<FunctionDecl>(CDRE->getDecl()))
3704 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003705 }
3706 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3707 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3708 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00003709 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3710 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00003711 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003712 BlockDeclRefs.push_back(BDRE);
3713 }
3714
Steve Naroff54055232008-10-27 17:20:55 +00003715 return;
3716}
3717
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003718void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003719 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003720 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003721 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003722 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003723 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3724 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003725 GetInnerBlockDeclRefExprs(CBE->getBody(),
3726 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003727 InnerContexts);
3728 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003729 else
3730 GetInnerBlockDeclRefExprs(*CI,
3731 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003732 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003733
3734 }
3735 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003736 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003737 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003738 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003739 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003740 }
3741 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3742 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3743 if (Var->isFunctionOrMethodVarDecl())
3744 ImportedLocalExternalDecls.insert(Var);
3745 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003746
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003747 return;
3748}
3749
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003750/// convertFunctionTypeOfBlocks - This routine converts a function type
3751/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003752/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003753/// all block pointers to function pointers.
3754QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3755 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3756 // FTP will be null for closures that don't take arguments.
3757 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003758 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003759 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003760 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003761
3762 if (FTP) {
3763 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3764 E = FTP->arg_type_end(); I && (I != E); ++I) {
3765 QualType t = *I;
3766 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003767 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003768 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003769 ArgTypes.push_back(t);
3770 }
3771 }
3772 QualType FuncType;
3773 // FIXME. Does this work if block takes no argument but has a return type
3774 // which is of block type?
3775 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003776 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003777 else FuncType = QualType(FT, 0);
3778 return FuncType;
3779}
3780
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003781Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003782 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003783 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003784
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003785 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003786 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003787 } else if (const BlockDeclRefExpr *CDRE =
3788 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003789 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003790 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003791 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003792 }
3793 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3794 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3795 }
3796 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3797 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3798 else if (const ConditionalOperator *CEXPR =
3799 dyn_cast<ConditionalOperator>(BlockExp)) {
3800 Expr *LHSExp = CEXPR->getLHS();
3801 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3802 Expr *RHSExp = CEXPR->getRHS();
3803 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3804 Expr *CONDExp = CEXPR->getCond();
3805 ConditionalOperator *CondExpr =
3806 new (Context) ConditionalOperator(CONDExp,
3807 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003808 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003809 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003810 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003811 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3812 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003813 } else if (const PseudoObjectExpr *POE
3814 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3815 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003816 } else {
3817 assert(1 && "RewriteBlockClass: Bad type");
3818 }
3819 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003820 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003821 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003822 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003823 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003825 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003826 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003827 &Context->Idents.get("__block_impl"));
3828 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003829
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003830 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003831 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003833 // Push the block argument type.
3834 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003835 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003836 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003837 E = FTP->arg_type_end(); I && (I != E); ++I) {
3838 QualType t = *I;
3839 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003840 if (!convertBlockPointerToFunctionPointer(t))
3841 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003842 ArgTypes.push_back(t);
3843 }
Steve Naroff54055232008-10-27 17:20:55 +00003844 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003845 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003846 QualType PtrToFuncCastType
3847 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003848
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003849 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003850
John McCall9d125032010-01-15 18:39:57 +00003851 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003852 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003853 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003854 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003855 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3856 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003857 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Douglas Gregor44b43212008-12-11 16:49:14 +00003859 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003860 SourceLocation(),
3861 &Context->Idents.get("FuncPtr"),
3862 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003863 /*BitWidth=*/0, /*Mutable=*/true,
3864 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003865 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003866 FD->getType(), VK_LValue,
3867 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003868
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003869
John McCall9d125032010-01-15 18:39:57 +00003870 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003871 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003872 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Chris Lattner5f9e2722011-07-23 10:55:15 +00003874 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003875 // Add the implicit argument.
3876 BlkExprs.push_back(BlkCast);
3877 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003878 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003879 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003880 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003881 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003882 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3883 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003884 Exp->getType(), VK_RValue,
3885 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003886 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003887}
3888
Steve Naroff621edce2009-04-29 16:37:50 +00003889// We need to return the rewritten expression to handle cases where the
3890// BlockDeclRefExpr is embedded in another expression being rewritten.
3891// For example:
3892//
3893// int main() {
3894// __block Foo *f;
3895// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003896//
Steve Naroff621edce2009-04-29 16:37:50 +00003897// void (^myblock)() = ^() {
3898// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3899// i = 77;
3900// };
3901//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003902Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003903 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003904 // for each DeclRefExp where BYREFVAR is name of the variable.
3905 ValueDecl *VD;
3906 bool isArrow = true;
3907 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3908 VD = BDRE->getDecl();
3909 else {
3910 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3911 isArrow = false;
3912 }
3913
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003914 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003915 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003916 &Context->Idents.get("__forwarding"),
3917 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003918 /*BitWidth=*/0, /*Mutable=*/true,
3919 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003920 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3921 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003922 FD->getType(), VK_LValue,
3923 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003924
Chris Lattner5f9e2722011-07-23 10:55:15 +00003925 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003926 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003927 &Context->Idents.get(Name),
3928 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003929 /*BitWidth=*/0, /*Mutable=*/true,
3930 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003931 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003932 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003933
3934
3935
Steve Naroffdf8570d2009-02-02 17:19:26 +00003936 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003937 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3938 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003939 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003940 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003941 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003942}
3943
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003944// Rewrites the imported local variable V with external storage
3945// (static, extern, etc.) as *V
3946//
3947Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3948 ValueDecl *VD = DRE->getDecl();
3949 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3950 if (!ImportedLocalExternalDecls.count(Var))
3951 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003952 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3953 VK_LValue, OK_Ordinary,
3954 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003955 // Need parens to enforce precedence.
3956 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3957 Exp);
3958 ReplaceStmt(DRE, PE);
3959 return PE;
3960}
3961
Steve Naroffb2f9e512008-11-03 23:29:32 +00003962void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3963 SourceLocation LocStart = CE->getLParenLoc();
3964 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003965
3966 // Need to avoid trying to rewrite synthesized casts.
3967 if (LocStart.isInvalid())
3968 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003969 // Need to avoid trying to rewrite casts contained in macros.
3970 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3971 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003972
Steve Naroff54055232008-10-27 17:20:55 +00003973 const char *startBuf = SM->getCharacterData(LocStart);
3974 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003975 QualType QT = CE->getType();
3976 const Type* TypePtr = QT->getAs<Type>();
3977 if (isa<TypeOfExprType>(TypePtr)) {
3978 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3979 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3980 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00003981 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003982 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003983 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003984 return;
3985 }
Steve Naroff54055232008-10-27 17:20:55 +00003986 // advance the location to startArgList.
3987 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Steve Naroff54055232008-10-27 17:20:55 +00003989 while (*argPtr++ && (argPtr < endBuf)) {
3990 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00003991 case '^':
3992 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003993 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003994 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00003995 break;
Steve Naroff54055232008-10-27 17:20:55 +00003996 }
3997 }
3998 return;
3999}
4000
4001void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4002 SourceLocation DeclLoc = FD->getLocation();
4003 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Steve Naroff54055232008-10-27 17:20:55 +00004005 // We have 1 or more arguments that have closure pointers.
4006 const char *startBuf = SM->getCharacterData(DeclLoc);
4007 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Steve Naroff54055232008-10-27 17:20:55 +00004009 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004010
Steve Naroff54055232008-10-27 17:20:55 +00004011 parenCount++;
4012 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004013 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004014 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Steve Naroff54055232008-10-27 17:20:55 +00004016 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Steve Naroff54055232008-10-27 17:20:55 +00004018 while (*argPtr++ && parenCount) {
4019 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004020 case '^':
4021 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004022 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004023 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004024 break;
4025 case '(':
4026 parenCount++;
4027 break;
4028 case ')':
4029 parenCount--;
4030 break;
Steve Naroff54055232008-10-27 17:20:55 +00004031 }
4032 }
4033 return;
4034}
4035
4036bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004037 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004038 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004039 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004040 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004041 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004042 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004043 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004044 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004045 }
4046 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004047 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004048 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004049 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004050 return true;
4051 }
4052 return false;
4053}
4054
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004055bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4056 const FunctionProtoType *FTP;
4057 const PointerType *PT = QT->getAs<PointerType>();
4058 if (PT) {
4059 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4060 } else {
4061 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4062 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4063 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4064 }
4065 if (FTP) {
4066 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004067 E = FTP->arg_type_end(); I != E; ++I) {
4068 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004069 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004070 if ((*I)->isObjCObjectPointerType() &&
4071 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4072 return true;
4073 }
4074
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004075 }
4076 return false;
4077}
4078
Ted Kremenek8189cde2009-02-07 01:47:29 +00004079void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4080 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004081 const char *argPtr = strchr(Name, '(');
4082 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004083
Steve Naroff54055232008-10-27 17:20:55 +00004084 LParen = argPtr; // output the start.
4085 argPtr++; // skip past the left paren.
4086 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004087
Steve Naroff54055232008-10-27 17:20:55 +00004088 while (*argPtr && parenCount) {
4089 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004090 case '(': parenCount++; break;
4091 case ')': parenCount--; break;
4092 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004093 }
4094 if (parenCount) argPtr++;
4095 }
4096 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4097 RParen = argPtr; // output the end
4098}
4099
4100void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4101 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4102 RewriteBlockPointerFunctionArgs(FD);
4103 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004104 }
Steve Naroff54055232008-10-27 17:20:55 +00004105 // Handle Variables and Typedefs.
4106 SourceLocation DeclLoc = ND->getLocation();
4107 QualType DeclT;
4108 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4109 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004110 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004111 DeclT = TDD->getUnderlyingType();
4112 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4113 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004114 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004115 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Steve Naroff54055232008-10-27 17:20:55 +00004117 const char *startBuf = SM->getCharacterData(DeclLoc);
4118 const char *endBuf = startBuf;
4119 // scan backward (from the decl location) for the end of the previous decl.
4120 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4121 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004122 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004123 std::string buf;
4124 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004125 // *startBuf != '^' if we are dealing with a pointer to function that
4126 // may take block argument types (which will be handled below).
4127 if (*startBuf == '^') {
4128 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004129 buf = '*';
4130 startBuf++;
4131 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004132 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004133 while (*startBuf != ')') {
4134 buf += *startBuf;
4135 startBuf++;
4136 OrigLength++;
4137 }
4138 buf += ')';
4139 OrigLength++;
4140
4141 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4142 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004143 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004144 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004145 DeclLoc = ND->getLocation();
4146 startBuf = SM->getCharacterData(DeclLoc);
4147 const char *argListBegin, *argListEnd;
4148 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4149 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004150 if (*argListBegin == '^')
4151 buf += '*';
4152 else if (*argListBegin == '<') {
4153 buf += "/*";
4154 buf += *argListBegin++;
4155 OrigLength++;;
4156 while (*argListBegin != '>') {
4157 buf += *argListBegin++;
4158 OrigLength++;
4159 }
4160 buf += *argListBegin;
4161 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004162 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004163 else
4164 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004165 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004166 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004167 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004168 buf += ')';
4169 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004170 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004171 ReplaceText(Start, OrigLength, buf);
4172
Steve Naroff54055232008-10-27 17:20:55 +00004173 return;
4174}
4175
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004176
4177/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4178/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4179/// struct Block_byref_id_object *src) {
4180/// _Block_object_assign (&_dest->object, _src->object,
4181/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4182/// [|BLOCK_FIELD_IS_WEAK]) // object
4183/// _Block_object_assign(&_dest->object, _src->object,
4184/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4185/// [|BLOCK_FIELD_IS_WEAK]) // block
4186/// }
4187/// And:
4188/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4189/// _Block_object_dispose(_src->object,
4190/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4191/// [|BLOCK_FIELD_IS_WEAK]) // object
4192/// _Block_object_dispose(_src->object,
4193/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4194/// [|BLOCK_FIELD_IS_WEAK]) // block
4195/// }
4196
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004197std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4198 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004199 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004200 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004201 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004202 CopyDestroyCache.insert(flag);
4203 S = "static void __Block_byref_id_object_copy_";
4204 S += utostr(flag);
4205 S += "(void *dst, void *src) {\n";
4206
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004207 // offset into the object pointer is computed as:
4208 // void * + void* + int + int + void* + void *
4209 unsigned IntSize =
4210 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4211 unsigned VoidPtrSize =
4212 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4213
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004214 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004215 S += " _Block_object_assign((char*)dst + ";
4216 S += utostr(offset);
4217 S += ", *(void * *) ((char*)src + ";
4218 S += utostr(offset);
4219 S += "), ";
4220 S += utostr(flag);
4221 S += ");\n}\n";
4222
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004223 S += "static void __Block_byref_id_object_dispose_";
4224 S += utostr(flag);
4225 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004226 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4227 S += utostr(offset);
4228 S += "), ";
4229 S += utostr(flag);
4230 S += ");\n}\n";
4231 return S;
4232}
4233
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004234/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4235/// the declaration into:
4236/// struct __Block_byref_ND {
4237/// void *__isa; // NULL for everything except __weak pointers
4238/// struct __Block_byref_ND *__forwarding;
4239/// int32_t __flags;
4240/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004241/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4242/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004243/// typex ND;
4244/// };
4245///
4246/// It then replaces declaration of ND variable with:
4247/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4248/// __size=sizeof(struct __Block_byref_ND),
4249/// ND=initializer-if-any};
4250///
4251///
4252void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004253 // Insert declaration for the function in which block literal is
4254 // used.
4255 if (CurFunctionDeclToDeclareForBlock)
4256 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004257 int flag = 0;
4258 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004259 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004260 if (DeclLoc.isInvalid())
4261 // If type location is missing, it is because of missing type (a warning).
4262 // Use variable's location which is good for this case.
4263 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004264 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004265 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004266 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004267 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004268 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004269 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004270 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004271 ByrefType += " {\n";
4272 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004273 RewriteByRefString(ByrefType, Name, ND);
4274 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004275 ByrefType += " int __flags;\n";
4276 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004277 // Add void *__Block_byref_id_object_copy;
4278 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004279 QualType Ty = ND->getType();
4280 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4281 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004282 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4283 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004284 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004285
4286 QualType T = Ty;
4287 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004288 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004289
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004290 ByrefType += " " + Name + ";\n";
4291 ByrefType += "};\n";
4292 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004293 SourceLocation FunLocStart;
4294 if (CurFunctionDef)
4295 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4296 else {
4297 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4298 FunLocStart = CurMethodDef->getLocStart();
4299 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004300 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004301 if (Ty.isObjCGCWeak()) {
4302 flag |= BLOCK_FIELD_IS_WEAK;
4303 isa = 1;
4304 }
4305
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004306 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004307 flag = BLOCK_BYREF_CALLER;
4308 QualType Ty = ND->getType();
4309 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4310 if (Ty->isBlockPointerType())
4311 flag |= BLOCK_FIELD_IS_BLOCK;
4312 else
4313 flag |= BLOCK_FIELD_IS_OBJECT;
4314 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004315 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004316 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004317 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004318
4319 // struct __Block_byref_ND ND =
4320 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4321 // initializer-if-any};
4322 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004323 unsigned flags = 0;
4324 if (HasCopyAndDispose)
4325 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004326 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004327 ByrefType.clear();
4328 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004329 std::string ForwardingCastType("(");
4330 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004331 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004332 ByrefType += " " + Name + " = {(void*)";
4333 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004334 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004335 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004336 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004337 ByrefType += "sizeof(";
4338 RewriteByRefString(ByrefType, Name, ND);
4339 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004340 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004341 ByrefType += ", __Block_byref_id_object_copy_";
4342 ByrefType += utostr(flag);
4343 ByrefType += ", __Block_byref_id_object_dispose_";
4344 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004345 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004346 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004347 unsigned nameSize = Name.size();
4348 // for block or function pointer declaration. Name is aleady
4349 // part of the declaration.
4350 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4351 nameSize = 1;
4352 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004353 }
4354 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004355 SourceLocation startLoc;
4356 Expr *E = ND->getInit();
4357 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4358 startLoc = ECE->getLParenLoc();
4359 else
4360 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004361 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004362 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004363 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004364 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004365 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004366 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004367 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004368 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004369 ByrefType += "sizeof(";
4370 RewriteByRefString(ByrefType, Name, ND);
4371 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004372 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004373 ByrefType += "__Block_byref_id_object_copy_";
4374 ByrefType += utostr(flag);
4375 ByrefType += ", __Block_byref_id_object_dispose_";
4376 ByrefType += utostr(flag);
4377 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004378 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004379 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004380
4381 // Complete the newly synthesized compound expression by inserting a right
4382 // curly brace before the end of the declaration.
4383 // FIXME: This approach avoids rewriting the initializer expression. It
4384 // also assumes there is only one declarator. For example, the following
4385 // isn't currently supported by this routine (in general):
4386 //
4387 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4388 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004389 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4390 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004391 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4392 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004393 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004394
Benjamin Kramerd999b372010-02-14 14:14:16 +00004395 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004396 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004397 return;
4398}
4399
Mike Stump1eb44332009-09-09 15:08:12 +00004400void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004401 // Add initializers for any closure decl refs.
4402 GetBlockDeclRefExprs(Exp->getBody());
4403 if (BlockDeclRefs.size()) {
4404 // Unique all "by copy" declarations.
4405 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004406 if (!BlockDeclRefs[i]->isByRef()) {
4407 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4408 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4409 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4410 }
4411 }
Steve Naroff54055232008-10-27 17:20:55 +00004412 // Unique all "by ref" declarations.
4413 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4414 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004415 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4416 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4417 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4418 }
Steve Naroff54055232008-10-27 17:20:55 +00004419 }
4420 // Find any imported blocks...they will need special attention.
4421 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004422 if (BlockDeclRefs[i]->isByRef() ||
4423 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004424 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004425 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004426 }
4427}
4428
Chris Lattner5f9e2722011-07-23 10:55:15 +00004429FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004430 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004431 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004432 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4433 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004434 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004435}
4436
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004437Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004438 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004439 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004440 Blocks.push_back(Exp);
4441
4442 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004443
4444 // Add inner imported variables now used in current block.
4445 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004446 if (!InnerBlockDeclRefs.empty()) {
4447 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4448 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4449 ValueDecl *VD = Exp->getDecl();
4450 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004451 // We need to save the copied-in variables in nested
4452 // blocks because it is needed at the end for some of the API generations.
4453 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004454 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4455 BlockDeclRefs.push_back(Exp);
4456 BlockByCopyDeclsPtrSet.insert(VD);
4457 BlockByCopyDecls.push_back(VD);
4458 }
4459 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4460 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4461 BlockDeclRefs.push_back(Exp);
4462 BlockByRefDeclsPtrSet.insert(VD);
4463 BlockByRefDecls.push_back(VD);
4464 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004465 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004466 // Find any imported blocks...they will need special attention.
4467 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4468 if (InnerBlockDeclRefs[i]->isByRef() ||
4469 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4470 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4471 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004472 }
4473 InnerDeclRefsCount.push_back(countOfInnerDecls);
4474
Steve Narofffa15fd92008-10-28 20:29:00 +00004475 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004476
Steve Narofffa15fd92008-10-28 20:29:00 +00004477 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004478 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004479 else if (CurMethodDef)
4480 BuildUniqueMethodName(FuncName, CurMethodDef);
4481 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004482 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004483
Steve Narofffa15fd92008-10-28 20:29:00 +00004484 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004485
Steve Narofffa15fd92008-10-28 20:29:00 +00004486 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4487 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004488
Steve Narofffa15fd92008-10-28 20:29:00 +00004489 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004490 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4491 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004492
4493 FunctionDecl *FD;
4494 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Steve Narofffa15fd92008-10-28 20:29:00 +00004496 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004497 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00004498 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4499 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004500
Chris Lattner5f9e2722011-07-23 10:55:15 +00004501 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004502
Steve Narofffdc03722008-10-29 21:23:59 +00004503 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004504 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00004505 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004506 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004507 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004508 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004509 InitExprs.push_back(castExpr);
4510
Steve Naroff01aec112009-12-06 21:14:13 +00004511 // Initialize the block descriptor.
4512 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004513
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004514 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4515 SourceLocation(), SourceLocation(),
4516 &Context->Idents.get(DescData.c_str()),
4517 Context->VoidPtrTy, 0,
4518 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004519 UnaryOperator *DescRefExpr =
4520 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4521 Context->VoidPtrTy,
4522 VK_LValue,
4523 SourceLocation()),
4524 UO_AddrOf,
4525 Context->getPointerType(Context->VoidPtrTy),
4526 VK_RValue, OK_Ordinary,
4527 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004528 InitExprs.push_back(DescRefExpr);
4529
Steve Narofffa15fd92008-10-28 20:29:00 +00004530 // Add initializers for any closure decl refs.
4531 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004532 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004533 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004534 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004535 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004536 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004537 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004538 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004539 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4540 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004541 if (HasLocalVariableExternalStorage(*I)) {
4542 QualType QT = (*I)->getType();
4543 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004544 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4545 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004546 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004547 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004548 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004549 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4550 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004551 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004552 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004553 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004554 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004555 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4556 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004557 if (HasLocalVariableExternalStorage(*I)) {
4558 QualType QT = (*I)->getType();
4559 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004560 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4561 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004562 }
4563
Steve Narofffa15fd92008-10-28 20:29:00 +00004564 }
Mike Stump1eb44332009-09-09 15:08:12 +00004565 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004566 }
4567 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004568 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004569 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004570 ValueDecl *ND = (*I);
4571 std::string Name(ND->getNameAsString());
4572 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004573 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004574 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4575 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004576 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004577 SourceLocation(), SourceLocation(),
4578 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004579 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4580 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4581
Daniel Dunbar4087f272010-08-17 22:39:59 +00004582 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004583 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4584 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004585 bool isNestedCapturedVar = false;
4586 if (block)
4587 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4588 ce = block->capture_end(); ci != ce; ++ci) {
4589 const VarDecl *variable = ci->getVariable();
4590 if (variable == ND && ci->isNested()) {
4591 assert (ci->isByRef() &&
4592 "SynthBlockInitExpr - captured block variable is not byref");
4593 isNestedCapturedVar = true;
4594 break;
4595 }
4596 }
4597 // captured nested byref variable has its address passed. Do not take
4598 // its address again.
4599 if (!isNestedCapturedVar)
4600 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004601 Context->getPointerType(Exp->getType()),
4602 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004603 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004604 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004605 }
4606 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004607 if (ImportedBlockDecls.size()) {
4608 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4609 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004610 unsigned IntSize =
4611 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004612 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4613 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004614 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004615 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004616 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004617 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004618 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004619 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004620 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004621 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004622 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004623 BlockDeclRefs.clear();
4624 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004625 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004626 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004627 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004628 ImportedBlockDecls.clear();
4629 return NewRep;
4630}
4631
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004632bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4633 if (const ObjCForCollectionStmt * CS =
4634 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4635 return CS->getElement() == DS;
4636 return false;
4637}
4638
Steve Narofffa15fd92008-10-28 20:29:00 +00004639//===----------------------------------------------------------------------===//
4640// Function Body / Expression rewriting
4641//===----------------------------------------------------------------------===//
4642
4643Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004644 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004645 isa<DoStmt>(S) || isa<ForStmt>(S))
4646 Stmts.push_back(S);
4647 else if (isa<ObjCForCollectionStmt>(S)) {
4648 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004649 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004650 }
Mike Stump1eb44332009-09-09 15:08:12 +00004651
John McCall4b9c2d22011-11-06 09:01:30 +00004652 // Pseudo-object operations and ivar references need special
4653 // treatment because we're going to recursively rewrite them.
4654 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4655 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4656 return RewritePropertyOrImplicitSetter(PseudoOp);
4657 } else {
4658 return RewritePropertyOrImplicitGetter(PseudoOp);
4659 }
4660 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4661 return RewriteObjCIvarRefExpr(IvarRefExpr);
4662 }
4663
Steve Narofffa15fd92008-10-28 20:29:00 +00004664 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Steve Narofffa15fd92008-10-28 20:29:00 +00004666 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004667 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004668 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004669 Stmt *childStmt = (*CI);
4670 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004671 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004672 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004673 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004674 }
Mike Stump1eb44332009-09-09 15:08:12 +00004675
Steve Narofffa15fd92008-10-28 20:29:00 +00004676 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004677 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004678 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4679 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004680 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004681 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004682 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004683 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004684 Stmt *SaveCurrentBody = CurrentBody;
4685 CurrentBody = BE->getBody();
4686 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004687 // block literal on rhs of a property-dot-sytax assignment
4688 // must be replaced by its synthesize ast so getRewrittenText
4689 // works as expected. In this case, what actually ends up on RHS
4690 // is the blockTranscribed which is the helper function for the
4691 // block literal; as in: self.c = ^() {[ace ARR];};
4692 bool saveDisableReplaceStmt = DisableReplaceStmt;
4693 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004694 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004695 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004696 CurrentBody = SaveCurrentBody;
4697 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004698 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004699 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004700 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004701 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004702
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004703 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4704
Steve Narofffa15fd92008-10-28 20:29:00 +00004705 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004706 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004707 return blockTranscribed;
4708 }
4709 // Handle specific things.
4710 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4711 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Steve Narofffa15fd92008-10-28 20:29:00 +00004713 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4714 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Steve Narofffa15fd92008-10-28 20:29:00 +00004716 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4717 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Steve Narofffa15fd92008-10-28 20:29:00 +00004719 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004720#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004721 // Before we rewrite it, put the original message expression in a comment.
4722 SourceLocation startLoc = MessExpr->getLocStart();
4723 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Steve Narofffa15fd92008-10-28 20:29:00 +00004725 const char *startBuf = SM->getCharacterData(startLoc);
4726 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Steve Narofffa15fd92008-10-28 20:29:00 +00004728 std::string messString;
4729 messString += "// ";
4730 messString.append(startBuf, endBuf-startBuf+1);
4731 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004732
4733 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004734 // InsertText(clang::SourceLocation, char const*, unsigned int).
4735 // InsertText(startLoc, messString.c_str(), messString.size());
4736 // Tried this, but it didn't work either...
4737 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004738#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004739 return RewriteMessageExpr(MessExpr);
4740 }
Mike Stump1eb44332009-09-09 15:08:12 +00004741
Steve Narofffa15fd92008-10-28 20:29:00 +00004742 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4743 return RewriteObjCTryStmt(StmtTry);
4744
4745 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4746 return RewriteObjCSynchronizedStmt(StmtTry);
4747
4748 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4749 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004750
Steve Narofffa15fd92008-10-28 20:29:00 +00004751 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4752 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004753
4754 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004755 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004756 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004757 OrigStmtRange.getEnd());
4758 if (BreakStmt *StmtBreakStmt =
4759 dyn_cast<BreakStmt>(S))
4760 return RewriteBreakStmt(StmtBreakStmt);
4761 if (ContinueStmt *StmtContinueStmt =
4762 dyn_cast<ContinueStmt>(S))
4763 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004764
4765 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004766 // and cast exprs.
4767 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4768 // FIXME: What we're doing here is modifying the type-specifier that
4769 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004770 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004771 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4772 // the context of an ObjCForCollectionStmt. For example:
4773 // NSArray *someArray;
4774 // for (id <FooProtocol> index in someArray) ;
4775 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4776 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004777 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004778 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004779
Steve Narofffa15fd92008-10-28 20:29:00 +00004780 // Blocks rewrite rules.
4781 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4782 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004783 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004784 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004785 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004786 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004787 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004788 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004789 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004790 if (VD->hasAttr<BlocksAttr>()) {
4791 static unsigned uniqueByrefDeclCount = 0;
4792 assert(!BlockByRefDeclNo.count(ND) &&
4793 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4794 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004795 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004796 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004797 else
4798 RewriteTypeOfDecl(VD);
4799 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004800 }
Richard Smith162e1c12011-04-15 14:24:37 +00004801 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004802 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004803 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004804 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004805 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4806 }
4807 }
4808 }
Mike Stump1eb44332009-09-09 15:08:12 +00004809
Steve Narofffa15fd92008-10-28 20:29:00 +00004810 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4811 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004812
4813 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004814 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4815 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004816 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4817 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004818 && "Statement stack mismatch");
4819 Stmts.pop_back();
4820 }
4821 // Handle blocks rewriting.
4822 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4823 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004824 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004825 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004826 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4827 ValueDecl *VD = DRE->getDecl();
4828 if (VD->hasAttr<BlocksAttr>())
4829 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004830 if (HasLocalVariableExternalStorage(VD))
4831 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004832 }
4833
Steve Narofffa15fd92008-10-28 20:29:00 +00004834 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004835 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004836 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004837 ReplaceStmt(S, BlockCall);
4838 return BlockCall;
4839 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004840 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004841 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004842 RewriteCastExpr(CE);
4843 }
4844#if 0
4845 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004846 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4847 ICE->getSubExpr(),
4848 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004849 // Get the new text.
4850 std::string SStr;
4851 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004852 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004853 const std::string &Str = Buf.str();
4854
4855 printf("CAST = %s\n", &Str[0]);
4856 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4857 delete S;
4858 return Replacement;
4859 }
4860#endif
4861 // Return this stmt unmodified.
4862 return S;
4863}
4864
Steve Naroff3d7e7862009-12-05 15:55:59 +00004865void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4866 for (RecordDecl::field_iterator i = RD->field_begin(),
4867 e = RD->field_end(); i != e; ++i) {
4868 FieldDecl *FD = *i;
4869 if (isTopLevelBlockPointerType(FD->getType()))
4870 RewriteBlockPointerDecl(FD);
4871 if (FD->getType()->isObjCQualifiedIdType() ||
4872 FD->getType()->isObjCQualifiedInterfaceType())
4873 RewriteObjCQualifiedInterfaceTypes(FD);
4874 }
4875}
4876
Steve Narofffa15fd92008-10-28 20:29:00 +00004877/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4878/// main file of the input.
4879void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004880 switch (D->getKind()) {
4881 case Decl::Function: {
4882 FunctionDecl *FD = cast<FunctionDecl>(D);
4883 if (FD->isOverloadedOperator())
4884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004885
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004886 // Since function prototypes don't have ParmDecl's, we check the function
4887 // prototype. This enables us to rewrite function declarations and
4888 // definitions using the same code.
4889 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004890
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004891 // FIXME: If this should support Obj-C++, support CXXTryStmt
4892 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4893 CurFunctionDef = FD;
4894 CurFunctionDeclToDeclareForBlock = FD;
4895 CurrentBody = Body;
4896 Body =
4897 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4898 FD->setBody(Body);
4899 CurrentBody = 0;
4900 if (PropParentMap) {
4901 delete PropParentMap;
4902 PropParentMap = 0;
4903 }
4904 // This synthesizes and inserts the block "impl" struct, invoke function,
4905 // and any copy/dispose helper functions.
4906 InsertBlockLiteralsWithinFunction(FD);
4907 CurFunctionDef = 0;
4908 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004909 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004910 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004911 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004912 case Decl::ObjCMethod: {
4913 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4914 if (CompoundStmt *Body = MD->getCompoundBody()) {
4915 CurMethodDef = MD;
4916 CurrentBody = Body;
4917 Body =
4918 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4919 MD->setBody(Body);
4920 CurrentBody = 0;
4921 if (PropParentMap) {
4922 delete PropParentMap;
4923 PropParentMap = 0;
4924 }
4925 InsertBlockLiteralsWithinMethod(MD);
4926 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004927 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004928 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004929 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004930 case Decl::ObjCImplementation: {
4931 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4932 ClassImplementation.push_back(CI);
4933 break;
4934 }
4935 case Decl::ObjCCategoryImpl: {
4936 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4937 CategoryImplementation.push_back(CI);
4938 break;
4939 }
4940 case Decl::Var: {
4941 VarDecl *VD = cast<VarDecl>(D);
4942 RewriteObjCQualifiedInterfaceTypes(VD);
4943 if (isTopLevelBlockPointerType(VD->getType()))
4944 RewriteBlockPointerDecl(VD);
4945 else if (VD->getType()->isFunctionPointerType()) {
4946 CheckFunctionPointerDecl(VD->getType(), VD);
4947 if (VD->getInit()) {
4948 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4949 RewriteCastExpr(CE);
4950 }
4951 }
4952 } else if (VD->getType()->isRecordType()) {
4953 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4954 if (RD->isCompleteDefinition())
4955 RewriteRecordBody(RD);
4956 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004957 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004958 GlobalVarDecl = VD;
4959 CurrentBody = VD->getInit();
4960 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4961 CurrentBody = 0;
4962 if (PropParentMap) {
4963 delete PropParentMap;
4964 PropParentMap = 0;
4965 }
4966 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4967 GlobalVarDecl = 0;
4968
4969 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004970 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004971 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004972 }
4973 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004974 break;
4975 }
4976 case Decl::TypeAlias:
4977 case Decl::Typedef: {
4978 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4979 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4980 RewriteBlockPointerDecl(TD);
4981 else if (TD->getUnderlyingType()->isFunctionPointerType())
4982 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4983 }
4984 break;
4985 }
4986 case Decl::CXXRecord:
4987 case Decl::Record: {
4988 RecordDecl *RD = cast<RecordDecl>(D);
4989 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00004990 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004991 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004992 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004993 case Decl::ObjCClass: {
4994 llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
4995 break;
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004996 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004997 default:
4998 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004999 }
5000 // Nothing yet.
5001}
5002
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005003void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005004 if (Diags.hasErrorOccurred())
5005 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005006
Steve Narofffa15fd92008-10-28 20:29:00 +00005007 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005008
Steve Naroff621edce2009-04-29 16:37:50 +00005009 // Here's a great place to add any extra declarations that may be needed.
5010 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005011 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005012 E = ProtocolExprDecls.end(); I != E; ++I)
5013 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5014
Benjamin Kramerd999b372010-02-14 14:14:16 +00005015 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005016 if (ClassImplementation.size() || CategoryImplementation.size())
5017 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005018
Steve Narofffa15fd92008-10-28 20:29:00 +00005019 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5020 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005021 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005022 Rewrite.getRewriteBufferFor(MainFileID)) {
5023 //printf("Changed:\n");
5024 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5025 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005026 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005027 }
Steve Narofface66252008-11-13 20:07:04 +00005028
Steve Naroff621edce2009-04-29 16:37:50 +00005029 if (ClassImplementation.size() || CategoryImplementation.size() ||
5030 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005031 // Rewrite Objective-c meta data*
5032 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005033 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005034 // Emit metadata.
5035 *OutFile << ResultStr;
5036 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005037 OutFile->flush();
5038}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005039
5040void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5041 InitializeCommon(context);
5042
5043 // declaring objc_selector outside the parameter list removes a silly
5044 // scope related warning...
5045 if (IsHeader)
5046 Preamble = "#pragma once\n";
5047 Preamble += "struct objc_selector; struct objc_class;\n";
5048 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5049 Preamble += "struct objc_object *superClass; ";
5050 if (LangOpts.MicrosoftExt) {
5051 // Add a constructor for creating temporary objects.
5052 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5053 ": ";
5054 Preamble += "object(o), superClass(s) {} ";
5055 }
5056 Preamble += "};\n";
5057 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5058 Preamble += "typedef struct objc_object Protocol;\n";
5059 Preamble += "#define _REWRITER_typedef_Protocol\n";
5060 Preamble += "#endif\n";
5061 if (LangOpts.MicrosoftExt) {
5062 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5063 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5064 } else
5065 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5066 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5067 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5068 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5069 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5070 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5071 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5072 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5073 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5074 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5075 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5076 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5077 Preamble += "(const char *);\n";
5078 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5079 Preamble += "(struct objc_class *);\n";
5080 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5081 Preamble += "(const char *);\n";
5082 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5083 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5084 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5085 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5086 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5087 Preamble += "(struct objc_class *, struct objc_object *);\n";
5088 // @synchronized hooks.
5089 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5090 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5091 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5092 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5093 Preamble += "struct __objcFastEnumerationState {\n\t";
5094 Preamble += "unsigned long state;\n\t";
5095 Preamble += "void **itemsPtr;\n\t";
5096 Preamble += "unsigned long *mutationsPtr;\n\t";
5097 Preamble += "unsigned long extra[5];\n};\n";
5098 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5099 Preamble += "#define __FASTENUMERATIONSTATE\n";
5100 Preamble += "#endif\n";
5101 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5102 Preamble += "struct __NSConstantStringImpl {\n";
5103 Preamble += " int *isa;\n";
5104 Preamble += " int flags;\n";
5105 Preamble += " char *str;\n";
5106 Preamble += " long length;\n";
5107 Preamble += "};\n";
5108 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5109 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5110 Preamble += "#else\n";
5111 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5112 Preamble += "#endif\n";
5113 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5114 Preamble += "#endif\n";
5115 // Blocks preamble.
5116 Preamble += "#ifndef BLOCK_IMPL\n";
5117 Preamble += "#define BLOCK_IMPL\n";
5118 Preamble += "struct __block_impl {\n";
5119 Preamble += " void *isa;\n";
5120 Preamble += " int Flags;\n";
5121 Preamble += " int Reserved;\n";
5122 Preamble += " void *FuncPtr;\n";
5123 Preamble += "};\n";
5124 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5125 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5126 Preamble += "extern \"C\" __declspec(dllexport) "
5127 "void _Block_object_assign(void *, const void *, const int);\n";
5128 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5129 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5130 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5131 Preamble += "#else\n";
5132 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5133 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5134 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5135 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5136 Preamble += "#endif\n";
5137 Preamble += "#endif\n";
5138 if (LangOpts.MicrosoftExt) {
5139 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5140 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5141 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5142 Preamble += "#define __attribute__(X)\n";
5143 Preamble += "#endif\n";
5144 Preamble += "#define __weak\n";
5145 }
5146 else {
5147 Preamble += "#define __block\n";
5148 Preamble += "#define __weak\n";
5149 }
5150 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5151 // as this avoids warning in any 64bit/32bit compilation model.
5152 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5153}
5154
5155/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5156/// ivar offset.
5157void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5158 std::string &Result) {
5159 if (ivar->isBitField()) {
5160 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5161 // place all bitfields at offset 0.
5162 Result += "0";
5163 } else {
5164 Result += "__OFFSETOFIVAR__(struct ";
5165 Result += ivar->getContainingInterface()->getNameAsString();
5166 if (LangOpts.MicrosoftExt)
5167 Result += "_IMPL";
5168 Result += ", ";
5169 Result += ivar->getNameAsString();
5170 Result += ")";
5171 }
5172}
5173
5174/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5175void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5176 ObjCProtocolDecl *PDecl, StringRef prefix,
5177 StringRef ClassName, std::string &Result) {
5178 static bool objc_protocol_methods = false;
5179
5180 // Output struct protocol_methods holder of method selector and type.
5181 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
5182 /* struct protocol_methods {
5183 SEL _cmd;
5184 char *method_types;
5185 }
5186 */
5187 Result += "\nstruct _protocol_methods {\n";
5188 Result += "\tstruct objc_selector *_cmd;\n";
5189 Result += "\tchar *method_types;\n";
5190 Result += "};\n";
5191
5192 objc_protocol_methods = true;
5193 }
5194 // Do not synthesize the protocol more than once.
5195 if (ObjCSynthesizedProtocols.count(PDecl))
5196 return;
5197
5198 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5199 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5200 PDecl->instmeth_end());
5201 /* struct _objc_protocol_method_list {
5202 int protocol_method_count;
5203 struct protocol_methods protocols[];
5204 }
5205 */
5206 Result += "\nstatic struct {\n";
5207 Result += "\tint protocol_method_count;\n";
5208 Result += "\tstruct _protocol_methods protocol_methods[";
5209 Result += utostr(NumMethods);
5210 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5211 Result += PDecl->getNameAsString();
5212 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5213 "{\n\t" + utostr(NumMethods) + "\n";
5214
5215 // Output instance methods declared in this protocol.
5216 for (ObjCProtocolDecl::instmeth_iterator
5217 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5218 I != E; ++I) {
5219 if (I == PDecl->instmeth_begin())
5220 Result += "\t ,{{(struct objc_selector *)\"";
5221 else
5222 Result += "\t ,{(struct objc_selector *)\"";
5223 Result += (*I)->getSelector().getAsString();
5224 std::string MethodTypeString;
5225 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5226 Result += "\", \"";
5227 Result += MethodTypeString;
5228 Result += "\"}\n";
5229 }
5230 Result += "\t }\n};\n";
5231 }
5232
5233 // Output class methods declared in this protocol.
5234 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5235 PDecl->classmeth_end());
5236 if (NumMethods > 0) {
5237 /* struct _objc_protocol_method_list {
5238 int protocol_method_count;
5239 struct protocol_methods protocols[];
5240 }
5241 */
5242 Result += "\nstatic struct {\n";
5243 Result += "\tint protocol_method_count;\n";
5244 Result += "\tstruct _protocol_methods protocol_methods[";
5245 Result += utostr(NumMethods);
5246 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5247 Result += PDecl->getNameAsString();
5248 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5249 "{\n\t";
5250 Result += utostr(NumMethods);
5251 Result += "\n";
5252
5253 // Output instance methods declared in this protocol.
5254 for (ObjCProtocolDecl::classmeth_iterator
5255 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5256 I != E; ++I) {
5257 if (I == PDecl->classmeth_begin())
5258 Result += "\t ,{{(struct objc_selector *)\"";
5259 else
5260 Result += "\t ,{(struct objc_selector *)\"";
5261 Result += (*I)->getSelector().getAsString();
5262 std::string MethodTypeString;
5263 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5264 Result += "\", \"";
5265 Result += MethodTypeString;
5266 Result += "\"}\n";
5267 }
5268 Result += "\t }\n};\n";
5269 }
5270
5271 // Output:
5272 /* struct _objc_protocol {
5273 // Objective-C 1.0 extensions
5274 struct _objc_protocol_extension *isa;
5275 char *protocol_name;
5276 struct _objc_protocol **protocol_list;
5277 struct _objc_protocol_method_list *instance_methods;
5278 struct _objc_protocol_method_list *class_methods;
5279 };
5280 */
5281 static bool objc_protocol = false;
5282 if (!objc_protocol) {
5283 Result += "\nstruct _objc_protocol {\n";
5284 Result += "\tstruct _objc_protocol_extension *isa;\n";
5285 Result += "\tchar *protocol_name;\n";
5286 Result += "\tstruct _objc_protocol **protocol_list;\n";
5287 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5288 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5289 Result += "};\n";
5290
5291 objc_protocol = true;
5292 }
5293
5294 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5295 Result += PDecl->getNameAsString();
5296 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5297 "{\n\t0, \"";
5298 Result += PDecl->getNameAsString();
5299 Result += "\", 0, ";
5300 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5301 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5302 Result += PDecl->getNameAsString();
5303 Result += ", ";
5304 }
5305 else
5306 Result += "0, ";
5307 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5308 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5309 Result += PDecl->getNameAsString();
5310 Result += "\n";
5311 }
5312 else
5313 Result += "0\n";
5314 Result += "};\n";
5315
5316 // Mark this protocol as having been generated.
5317 if (!ObjCSynthesizedProtocols.insert(PDecl))
5318 llvm_unreachable("protocol already synthesized");
5319
5320}
5321
5322void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5323 const ObjCList<ObjCProtocolDecl> &Protocols,
5324 StringRef prefix, StringRef ClassName,
5325 std::string &Result) {
5326 if (Protocols.empty()) return;
5327
5328 for (unsigned i = 0; i != Protocols.size(); i++)
5329 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5330
5331 // Output the top lovel protocol meta-data for the class.
5332 /* struct _objc_protocol_list {
5333 struct _objc_protocol_list *next;
5334 int protocol_count;
5335 struct _objc_protocol *class_protocols[];
5336 }
5337 */
5338 Result += "\nstatic struct {\n";
5339 Result += "\tstruct _objc_protocol_list *next;\n";
5340 Result += "\tint protocol_count;\n";
5341 Result += "\tstruct _objc_protocol *class_protocols[";
5342 Result += utostr(Protocols.size());
5343 Result += "];\n} _OBJC_";
5344 Result += prefix;
5345 Result += "_PROTOCOLS_";
5346 Result += ClassName;
5347 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5348 "{\n\t0, ";
5349 Result += utostr(Protocols.size());
5350 Result += "\n";
5351
5352 Result += "\t,{&_OBJC_PROTOCOL_";
5353 Result += Protocols[0]->getNameAsString();
5354 Result += " \n";
5355
5356 for (unsigned i = 1; i != Protocols.size(); i++) {
5357 Result += "\t ,&_OBJC_PROTOCOL_";
5358 Result += Protocols[i]->getNameAsString();
5359 Result += "\n";
5360 }
5361 Result += "\t }\n};\n";
5362}
5363
5364void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5365 std::string &Result) {
5366 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5367
5368 // Explicitly declared @interface's are already synthesized.
5369 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005370 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005371 // produce correct synthesis as yet.
5372 RewriteObjCInternalStruct(CDecl, Result);
5373 }
5374
5375 // Build _objc_ivar_list metadata for classes ivars if needed
5376 unsigned NumIvars = !IDecl->ivar_empty()
5377 ? IDecl->ivar_size()
5378 : (CDecl ? CDecl->ivar_size() : 0);
5379 if (NumIvars > 0) {
5380 static bool objc_ivar = false;
5381 if (!objc_ivar) {
5382 /* struct _objc_ivar {
5383 char *ivar_name;
5384 char *ivar_type;
5385 int ivar_offset;
5386 };
5387 */
5388 Result += "\nstruct _objc_ivar {\n";
5389 Result += "\tchar *ivar_name;\n";
5390 Result += "\tchar *ivar_type;\n";
5391 Result += "\tint ivar_offset;\n";
5392 Result += "};\n";
5393
5394 objc_ivar = true;
5395 }
5396
5397 /* struct {
5398 int ivar_count;
5399 struct _objc_ivar ivar_list[nIvars];
5400 };
5401 */
5402 Result += "\nstatic struct {\n";
5403 Result += "\tint ivar_count;\n";
5404 Result += "\tstruct _objc_ivar ivar_list[";
5405 Result += utostr(NumIvars);
5406 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5407 Result += IDecl->getNameAsString();
5408 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5409 "{\n\t";
5410 Result += utostr(NumIvars);
5411 Result += "\n";
5412
5413 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5414 SmallVector<ObjCIvarDecl *, 8> IVars;
5415 if (!IDecl->ivar_empty()) {
5416 for (ObjCInterfaceDecl::ivar_iterator
5417 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5418 IV != IVEnd; ++IV)
5419 IVars.push_back(*IV);
5420 IVI = IDecl->ivar_begin();
5421 IVE = IDecl->ivar_end();
5422 } else {
5423 IVI = CDecl->ivar_begin();
5424 IVE = CDecl->ivar_end();
5425 }
5426 Result += "\t,{{\"";
5427 Result += (*IVI)->getNameAsString();
5428 Result += "\", \"";
5429 std::string TmpString, StrEncoding;
5430 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5431 QuoteDoublequotes(TmpString, StrEncoding);
5432 Result += StrEncoding;
5433 Result += "\", ";
5434 RewriteIvarOffsetComputation(*IVI, Result);
5435 Result += "}\n";
5436 for (++IVI; IVI != IVE; ++IVI) {
5437 Result += "\t ,{\"";
5438 Result += (*IVI)->getNameAsString();
5439 Result += "\", \"";
5440 std::string TmpString, StrEncoding;
5441 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5442 QuoteDoublequotes(TmpString, StrEncoding);
5443 Result += StrEncoding;
5444 Result += "\", ";
5445 RewriteIvarOffsetComputation((*IVI), Result);
5446 Result += "}\n";
5447 }
5448
5449 Result += "\t }\n};\n";
5450 }
5451
5452 // Build _objc_method_list for class's instance methods if needed
5453 SmallVector<ObjCMethodDecl *, 32>
5454 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5455
5456 // If any of our property implementations have associated getters or
5457 // setters, produce metadata for them as well.
5458 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5459 PropEnd = IDecl->propimpl_end();
5460 Prop != PropEnd; ++Prop) {
5461 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5462 continue;
5463 if (!(*Prop)->getPropertyIvarDecl())
5464 continue;
5465 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5466 if (!PD)
5467 continue;
5468 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5469 if (!Getter->isDefined())
5470 InstanceMethods.push_back(Getter);
5471 if (PD->isReadOnly())
5472 continue;
5473 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5474 if (!Setter->isDefined())
5475 InstanceMethods.push_back(Setter);
5476 }
5477 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5478 true, "", IDecl->getName(), Result);
5479
5480 // Build _objc_method_list for class's class methods if needed
5481 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5482 false, "", IDecl->getName(), Result);
5483
5484 // Protocols referenced in class declaration?
5485 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5486 "CLASS", CDecl->getName(), Result);
5487
5488 // Declaration of class/meta-class metadata
5489 /* struct _objc_class {
5490 struct _objc_class *isa; // or const char *root_class_name when metadata
5491 const char *super_class_name;
5492 char *name;
5493 long version;
5494 long info;
5495 long instance_size;
5496 struct _objc_ivar_list *ivars;
5497 struct _objc_method_list *methods;
5498 struct objc_cache *cache;
5499 struct objc_protocol_list *protocols;
5500 const char *ivar_layout;
5501 struct _objc_class_ext *ext;
5502 };
5503 */
5504 static bool objc_class = false;
5505 if (!objc_class) {
5506 Result += "\nstruct _objc_class {\n";
5507 Result += "\tstruct _objc_class *isa;\n";
5508 Result += "\tconst char *super_class_name;\n";
5509 Result += "\tchar *name;\n";
5510 Result += "\tlong version;\n";
5511 Result += "\tlong info;\n";
5512 Result += "\tlong instance_size;\n";
5513 Result += "\tstruct _objc_ivar_list *ivars;\n";
5514 Result += "\tstruct _objc_method_list *methods;\n";
5515 Result += "\tstruct objc_cache *cache;\n";
5516 Result += "\tstruct _objc_protocol_list *protocols;\n";
5517 Result += "\tconst char *ivar_layout;\n";
5518 Result += "\tstruct _objc_class_ext *ext;\n";
5519 Result += "};\n";
5520 objc_class = true;
5521 }
5522
5523 // Meta-class metadata generation.
5524 ObjCInterfaceDecl *RootClass = 0;
5525 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5526 while (SuperClass) {
5527 RootClass = SuperClass;
5528 SuperClass = SuperClass->getSuperClass();
5529 }
5530 SuperClass = CDecl->getSuperClass();
5531
5532 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5533 Result += CDecl->getNameAsString();
5534 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5535 "{\n\t(struct _objc_class *)\"";
5536 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5537 Result += "\"";
5538
5539 if (SuperClass) {
5540 Result += ", \"";
5541 Result += SuperClass->getNameAsString();
5542 Result += "\", \"";
5543 Result += CDecl->getNameAsString();
5544 Result += "\"";
5545 }
5546 else {
5547 Result += ", 0, \"";
5548 Result += CDecl->getNameAsString();
5549 Result += "\"";
5550 }
5551 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5552 // 'info' field is initialized to CLS_META(2) for metaclass
5553 Result += ", 0,2, sizeof(struct _objc_class), 0";
5554 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5555 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5556 Result += IDecl->getNameAsString();
5557 Result += "\n";
5558 }
5559 else
5560 Result += ", 0\n";
5561 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5562 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5563 Result += CDecl->getNameAsString();
5564 Result += ",0,0\n";
5565 }
5566 else
5567 Result += "\t,0,0,0,0\n";
5568 Result += "};\n";
5569
5570 // class metadata generation.
5571 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5572 Result += CDecl->getNameAsString();
5573 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5574 "{\n\t&_OBJC_METACLASS_";
5575 Result += CDecl->getNameAsString();
5576 if (SuperClass) {
5577 Result += ", \"";
5578 Result += SuperClass->getNameAsString();
5579 Result += "\", \"";
5580 Result += CDecl->getNameAsString();
5581 Result += "\"";
5582 }
5583 else {
5584 Result += ", 0, \"";
5585 Result += CDecl->getNameAsString();
5586 Result += "\"";
5587 }
5588 // 'info' field is initialized to CLS_CLASS(1) for class
5589 Result += ", 0,1";
5590 if (!ObjCSynthesizedStructs.count(CDecl))
5591 Result += ",0";
5592 else {
5593 // class has size. Must synthesize its size.
5594 Result += ",sizeof(struct ";
5595 Result += CDecl->getNameAsString();
5596 if (LangOpts.MicrosoftExt)
5597 Result += "_IMPL";
5598 Result += ")";
5599 }
5600 if (NumIvars > 0) {
5601 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5602 Result += CDecl->getNameAsString();
5603 Result += "\n\t";
5604 }
5605 else
5606 Result += ",0";
5607 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5608 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5609 Result += CDecl->getNameAsString();
5610 Result += ", 0\n\t";
5611 }
5612 else
5613 Result += ",0,0";
5614 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5615 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5616 Result += CDecl->getNameAsString();
5617 Result += ", 0,0\n";
5618 }
5619 else
5620 Result += ",0,0,0\n";
5621 Result += "};\n";
5622}
5623
5624void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5625 int ClsDefCount = ClassImplementation.size();
5626 int CatDefCount = CategoryImplementation.size();
5627
5628 // For each implemented class, write out all its meta data.
5629 for (int i = 0; i < ClsDefCount; i++)
5630 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5631
5632 // For each implemented category, write out all its meta data.
5633 for (int i = 0; i < CatDefCount; i++)
5634 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5635
5636 // Write objc_symtab metadata
5637 /*
5638 struct _objc_symtab
5639 {
5640 long sel_ref_cnt;
5641 SEL *refs;
5642 short cls_def_cnt;
5643 short cat_def_cnt;
5644 void *defs[cls_def_cnt + cat_def_cnt];
5645 };
5646 */
5647
5648 Result += "\nstruct _objc_symtab {\n";
5649 Result += "\tlong sel_ref_cnt;\n";
5650 Result += "\tSEL *refs;\n";
5651 Result += "\tshort cls_def_cnt;\n";
5652 Result += "\tshort cat_def_cnt;\n";
5653 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5654 Result += "};\n\n";
5655
5656 Result += "static struct _objc_symtab "
5657 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5658 Result += "\t0, 0, " + utostr(ClsDefCount)
5659 + ", " + utostr(CatDefCount) + "\n";
5660 for (int i = 0; i < ClsDefCount; i++) {
5661 Result += "\t,&_OBJC_CLASS_";
5662 Result += ClassImplementation[i]->getNameAsString();
5663 Result += "\n";
5664 }
5665
5666 for (int i = 0; i < CatDefCount; i++) {
5667 Result += "\t,&_OBJC_CATEGORY_";
5668 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5669 Result += "_";
5670 Result += CategoryImplementation[i]->getNameAsString();
5671 Result += "\n";
5672 }
5673
5674 Result += "};\n\n";
5675
5676 // Write objc_module metadata
5677
5678 /*
5679 struct _objc_module {
5680 long version;
5681 long size;
5682 const char *name;
5683 struct _objc_symtab *symtab;
5684 }
5685 */
5686
5687 Result += "\nstruct _objc_module {\n";
5688 Result += "\tlong version;\n";
5689 Result += "\tlong size;\n";
5690 Result += "\tconst char *name;\n";
5691 Result += "\tstruct _objc_symtab *symtab;\n";
5692 Result += "};\n\n";
5693 Result += "static struct _objc_module "
5694 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5695 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5696 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5697 Result += "};\n\n";
5698
5699 if (LangOpts.MicrosoftExt) {
5700 if (ProtocolExprDecls.size()) {
5701 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5702 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5703 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5704 E = ProtocolExprDecls.end(); I != E; ++I) {
5705 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5706 Result += (*I)->getNameAsString();
5707 Result += " = &_OBJC_PROTOCOL_";
5708 Result += (*I)->getNameAsString();
5709 Result += ";\n";
5710 }
5711 Result += "#pragma data_seg(pop)\n\n";
5712 }
5713 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5714 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5715 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5716 Result += "&_OBJC_MODULES;\n";
5717 Result += "#pragma data_seg(pop)\n\n";
5718 }
5719}
5720
5721/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5722/// implementation.
5723void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5724 std::string &Result) {
5725 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5726 // Find category declaration for this implementation.
5727 ObjCCategoryDecl *CDecl;
5728 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5729 CDecl = CDecl->getNextClassCategory())
5730 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5731 break;
5732
5733 std::string FullCategoryName = ClassDecl->getNameAsString();
5734 FullCategoryName += '_';
5735 FullCategoryName += IDecl->getNameAsString();
5736
5737 // Build _objc_method_list for class's instance methods if needed
5738 SmallVector<ObjCMethodDecl *, 32>
5739 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5740
5741 // If any of our property implementations have associated getters or
5742 // setters, produce metadata for them as well.
5743 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5744 PropEnd = IDecl->propimpl_end();
5745 Prop != PropEnd; ++Prop) {
5746 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5747 continue;
5748 if (!(*Prop)->getPropertyIvarDecl())
5749 continue;
5750 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5751 if (!PD)
5752 continue;
5753 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5754 InstanceMethods.push_back(Getter);
5755 if (PD->isReadOnly())
5756 continue;
5757 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5758 InstanceMethods.push_back(Setter);
5759 }
5760 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5761 true, "CATEGORY_", FullCategoryName.c_str(),
5762 Result);
5763
5764 // Build _objc_method_list for class's class methods if needed
5765 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5766 false, "CATEGORY_", FullCategoryName.c_str(),
5767 Result);
5768
5769 // Protocols referenced in class declaration?
5770 // Null CDecl is case of a category implementation with no category interface
5771 if (CDecl)
5772 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5773 FullCategoryName, Result);
5774 /* struct _objc_category {
5775 char *category_name;
5776 char *class_name;
5777 struct _objc_method_list *instance_methods;
5778 struct _objc_method_list *class_methods;
5779 struct _objc_protocol_list *protocols;
5780 // Objective-C 1.0 extensions
5781 uint32_t size; // sizeof (struct _objc_category)
5782 struct _objc_property_list *instance_properties; // category's own
5783 // @property decl.
5784 };
5785 */
5786
5787 static bool objc_category = false;
5788 if (!objc_category) {
5789 Result += "\nstruct _objc_category {\n";
5790 Result += "\tchar *category_name;\n";
5791 Result += "\tchar *class_name;\n";
5792 Result += "\tstruct _objc_method_list *instance_methods;\n";
5793 Result += "\tstruct _objc_method_list *class_methods;\n";
5794 Result += "\tstruct _objc_protocol_list *protocols;\n";
5795 Result += "\tunsigned int size;\n";
5796 Result += "\tstruct _objc_property_list *instance_properties;\n";
5797 Result += "};\n";
5798 objc_category = true;
5799 }
5800 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5801 Result += FullCategoryName;
5802 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5803 Result += IDecl->getNameAsString();
5804 Result += "\"\n\t, \"";
5805 Result += ClassDecl->getNameAsString();
5806 Result += "\"\n";
5807
5808 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5809 Result += "\t, (struct _objc_method_list *)"
5810 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5811 Result += FullCategoryName;
5812 Result += "\n";
5813 }
5814 else
5815 Result += "\t, 0\n";
5816 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5817 Result += "\t, (struct _objc_method_list *)"
5818 "&_OBJC_CATEGORY_CLASS_METHODS_";
5819 Result += FullCategoryName;
5820 Result += "\n";
5821 }
5822 else
5823 Result += "\t, 0\n";
5824
5825 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5826 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5827 Result += FullCategoryName;
5828 Result += "\n";
5829 }
5830 else
5831 Result += "\t, 0\n";
5832 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5833}
5834
5835// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5836/// class methods.
5837template<typename MethodIterator>
5838void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5839 MethodIterator MethodEnd,
5840 bool IsInstanceMethod,
5841 StringRef prefix,
5842 StringRef ClassName,
5843 std::string &Result) {
5844 if (MethodBegin == MethodEnd) return;
5845
5846 if (!objc_impl_method) {
5847 /* struct _objc_method {
5848 SEL _cmd;
5849 char *method_types;
5850 void *_imp;
5851 }
5852 */
5853 Result += "\nstruct _objc_method {\n";
5854 Result += "\tSEL _cmd;\n";
5855 Result += "\tchar *method_types;\n";
5856 Result += "\tvoid *_imp;\n";
5857 Result += "};\n";
5858
5859 objc_impl_method = true;
5860 }
5861
5862 // Build _objc_method_list for class's methods if needed
5863
5864 /* struct {
5865 struct _objc_method_list *next_method;
5866 int method_count;
5867 struct _objc_method method_list[];
5868 }
5869 */
5870 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5871 Result += "\nstatic struct {\n";
5872 Result += "\tstruct _objc_method_list *next_method;\n";
5873 Result += "\tint method_count;\n";
5874 Result += "\tstruct _objc_method method_list[";
5875 Result += utostr(NumMethods);
5876 Result += "];\n} _OBJC_";
5877 Result += prefix;
5878 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5879 Result += "_METHODS_";
5880 Result += ClassName;
5881 Result += " __attribute__ ((used, section (\"__OBJC, __";
5882 Result += IsInstanceMethod ? "inst" : "cls";
5883 Result += "_meth\")))= ";
5884 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5885
5886 Result += "\t,{{(SEL)\"";
5887 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5888 std::string MethodTypeString;
5889 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5890 Result += "\", \"";
5891 Result += MethodTypeString;
5892 Result += "\", (void *)";
5893 Result += MethodInternalNames[*MethodBegin];
5894 Result += "}\n";
5895 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5896 Result += "\t ,{(SEL)\"";
5897 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5898 std::string MethodTypeString;
5899 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5900 Result += "\", \"";
5901 Result += MethodTypeString;
5902 Result += "\", (void *)";
5903 Result += MethodInternalNames[*MethodBegin];
5904 Result += "}\n";
5905 }
5906 Result += "\t }\n};\n";
5907}
5908
5909Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5910 SourceRange OldRange = IV->getSourceRange();
5911 Expr *BaseExpr = IV->getBase();
5912
5913 // Rewrite the base, but without actually doing replaces.
5914 {
5915 DisableReplaceStmtScope S(*this);
5916 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5917 IV->setBase(BaseExpr);
5918 }
5919
5920 ObjCIvarDecl *D = IV->getDecl();
5921
5922 Expr *Replacement = IV;
5923 if (CurMethodDef) {
5924 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5925 const ObjCInterfaceType *iFaceDecl =
5926 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5927 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5928 // lookup which class implements the instance variable.
5929 ObjCInterfaceDecl *clsDeclared = 0;
5930 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5931 clsDeclared);
5932 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5933
5934 // Synthesize an explicit cast to gain access to the ivar.
5935 std::string RecName = clsDeclared->getIdentifier()->getName();
5936 RecName += "_IMPL";
5937 IdentifierInfo *II = &Context->Idents.get(RecName);
5938 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5939 SourceLocation(), SourceLocation(),
5940 II);
5941 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5942 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5943 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5944 CK_BitCast,
5945 IV->getBase());
5946 // Don't forget the parens to enforce the proper binding.
5947 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5948 OldRange.getEnd(),
5949 castExpr);
5950 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005951 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005952 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5953 IV->getLocation(),
5954 D->getType(),
5955 VK_LValue, OK_Ordinary);
5956 Replacement = ME;
5957 } else {
5958 IV->setBase(PE);
5959 }
5960 }
5961 } else { // we are outside a method.
5962 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5963
5964 // Explicit ivar refs need to have a cast inserted.
5965 // FIXME: consider sharing some of this code with the code above.
5966 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5967 const ObjCInterfaceType *iFaceDecl =
5968 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5969 // lookup which class implements the instance variable.
5970 ObjCInterfaceDecl *clsDeclared = 0;
5971 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5972 clsDeclared);
5973 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5974
5975 // Synthesize an explicit cast to gain access to the ivar.
5976 std::string RecName = clsDeclared->getIdentifier()->getName();
5977 RecName += "_IMPL";
5978 IdentifierInfo *II = &Context->Idents.get(RecName);
5979 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5980 SourceLocation(), SourceLocation(),
5981 II);
5982 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5983 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5984 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5985 CK_BitCast,
5986 IV->getBase());
5987 // Don't forget the parens to enforce the proper binding.
5988 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5989 IV->getBase()->getLocEnd(), castExpr);
5990 // Cannot delete IV->getBase(), since PE points to it.
5991 // Replace the old base with the cast. This is important when doing
5992 // embedded rewrites. For example, [newInv->_container addObject:0].
5993 IV->setBase(PE);
5994 }
5995 }
5996
5997 ReplaceStmtWithRange(IV, Replacement, OldRange);
5998 return Replacement;
5999}
6000