blob: c7a567812efb085f18c58cdc54749724c468ab1a [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 Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000058 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
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;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner5f9e2722011-07-23 10:55:15 +000070 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000072 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 SmallVector<Stmt *, 32> Stmts;
77 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000127
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Nick Lewycky7e749242010-10-31 21:07:24 +0000158 static const int OBJC_ABI_VERSION = 7;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
165 if (isa<ObjCClassDecl>((*I))) {
166 RewriteForwardClassDecl(D);
167 break;
168 }
Chris Lattner682bf922009-03-29 16:50:03 +0000169 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000170 }
Chris Lattner682bf922009-03-29 16:50:03 +0000171 }
172 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000173 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000174 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000175 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000176 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000177
178 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000180 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000182 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000183 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Steve Naroff4c3580e2008-12-04 23:50:32 +0000185 if (ReplacingStmt)
186 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000187
Steve Naroffb619d952008-12-09 12:56:34 +0000188 if (DisableReplaceStmt)
189 return; // Used when rewriting the assignment of a property setter.
190
Steve Naroff4c3580e2008-12-04 23:50:32 +0000191 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000192 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000193 ReplacedNodes[Old] = New;
194 return;
195 }
196 if (SilenceRewriteMacroWarning)
197 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000198 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
199 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000200 }
Steve Naroffb619d952008-12-09 12:56:34 +0000201
202 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Nick Lewycky7e749242010-10-31 21:07:24 +0000203 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000204 int Size = Rewrite.getRangeSize(SrcRange);
205 if (Size == -1) {
206 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
207 << Old->getSourceRange();
208 return;
209 }
210 // Get the new text.
211 std::string SStr;
212 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000213 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000214 const std::string &Str = S.str();
215
216 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000217 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000218 ReplacedNodes[Old] = New;
219 return;
220 }
221 if (SilenceRewriteMacroWarning)
222 return;
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 }
226
Chris Lattner5f9e2722011-07-23 10:55:15 +0000227 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000228 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000229 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000230 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000231 SilenceRewriteMacroWarning)
232 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000234 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000240 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000241 SilenceRewriteMacroWarning)
242 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattnerf04da132007-10-24 17:06:59 +0000247 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000248 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000249 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000250 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
251 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
252 const std::string &typedefString);
253
Steve Naroffa0876e82008-12-02 17:36:43 +0000254 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
255 ObjCImplementationDecl *IMD,
256 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000257 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000258 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000259 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
260 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000264 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000271 void RewriteBlockPointerType(std::string& Str, QualType Type);
272 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000273 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000274 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000275 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000276 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000277 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000278 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000279 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000280 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000281 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnerf04da132007-10-24 17:06:59 +0000283 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000284 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000285 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Steve Naroff8599e7a2008-12-08 16:43:47 +0000287 Stmt *CurrentBody;
288 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattnere64b7772007-10-24 16:57:36 +0000290 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000291 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
292 bool &replaced);
293 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000294 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
295 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000296 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000297 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000298 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000299 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000300 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000301 void WarnAboutReturnGotoStmts(Stmt *S);
302 void HasReturnStmts(Stmt *S, bool &hasReturns);
303 void RewriteTryReturnStmts(Stmt *S);
304 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000306 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000308 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
309 SourceLocation OrigEnd);
Fariborz Jahanian42f1e652011-02-24 21:29:21 +0000310 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump1eb44332009-09-09 15:08:12 +0000311 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000312 Expr **args, unsigned nargs,
313 SourceLocation StartLoc=SourceLocation(),
314 SourceLocation EndLoc=SourceLocation());
315 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
316 SourceLocation StartLoc=SourceLocation(),
317 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000318 Stmt *RewriteBreakStmt(BreakStmt *S);
319 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000320 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Steve Naroff09b266e2007-10-30 23:14:51 +0000322 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000323 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000324 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000325 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000326 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000327 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000328 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000329 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000330 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000331 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattnerf04da132007-10-24 17:06:59 +0000333 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000334 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000335 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000337 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000338 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregor653f1b12009-04-23 01:02:12 +0000340 template<typename MethodIterator>
341 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
342 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000343 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000344 StringRef prefix,
345 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000346 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Steve Naroff621edce2009-04-29 16:37:50 +0000348 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000349 StringRef prefix,
350 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000351 std::string &Result);
352 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000353 StringRef prefix,
354 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000355 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000356 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000357 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000358 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000359 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000360 void RewriteImplementations();
361 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroff54055232008-10-27 17:20:55 +0000363 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000364 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000365 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Steve Naroff54055232008-10-27 17:20:55 +0000367 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
368 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
370 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000371 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000372 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000373 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000374 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000375 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000376 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000377
378 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000379 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000380 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000381 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000382 std::string SynthesizeBlockImpl(BlockExpr *CE,
383 std::string Tag, std::string Desc);
384 std::string SynthesizeBlockDescriptor(std::string DescTag,
385 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000386 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000387 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000388 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000389 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390 StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000391 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Steve Naroff54055232008-10-27 17:20:55 +0000393 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000394 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000395 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000396 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000397 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Steve Naroff54055232008-10-27 17:20:55 +0000399 // We avoid calling Type::isBlockPointerType(), since it operates on the
400 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000401 bool isTopLevelBlockPointerType(QualType T) {
402 return isa<BlockPointerType>(T);
403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000405 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
406 /// to a function pointer type and upon success, returns true; false
407 /// otherwise.
408 bool convertBlockPointerToFunctionPointer(QualType &T) {
409 if (isTopLevelBlockPointerType(T)) {
410 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
411 T = Context->getPointerType(BPT->getPointeeType());
412 return true;
413 }
414 return false;
415 }
416
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000417 void convertToUnqualifiedObjCType(QualType &T) {
418 if (T->isObjCQualifiedIdType())
419 T = Context->getObjCIdType();
420 else if (T->isObjCQualifiedClassType())
421 T = Context->getObjCClassType();
422 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000423 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
424 if (const ObjCObjectPointerType * OBJPT =
425 T->getAsObjCInterfacePointerType()) {
426 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
427 T = QualType(IFaceT, 0);
428 T = Context->getPointerType(T);
429 }
430 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000431 }
432
Steve Naroff54055232008-10-27 17:20:55 +0000433 // FIXME: This predicate seems like it would be useful to add to ASTContext.
434 bool isObjCType(QualType T) {
435 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
436 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Steve Naroff54055232008-10-27 17:20:55 +0000438 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Steve Naroff54055232008-10-27 17:20:55 +0000440 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
441 OCT == Context->getCanonicalType(Context->getObjCClassType()))
442 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Ted Kremenek6217b802009-07-29 21:53:49 +0000444 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000445 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000446 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000447 return true;
448 }
449 return false;
450 }
451 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000452 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000453 void GetExtentOfArgList(const char *Name, const char *&LParen,
454 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000455 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattner5f9e2722011-07-23 10:55:15 +0000457 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000458 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000459 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Steve Naroff621edce2009-04-29 16:37:50 +0000461 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000462 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000463 if (From[i] == '"')
464 To += "\\\"";
465 else
466 To += From[i];
467 }
468 }
John McCalle23cf432010-12-14 08:05:40 +0000469
470 QualType getSimpleFunctionType(QualType result,
471 const QualType *args,
472 unsigned numArgs,
473 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000474 if (result == Context->getObjCInstanceType())
475 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000476 FunctionProtoType::ExtProtoInfo fpi;
477 fpi.Variadic = variadic;
478 return Context->getFunctionType(result, args, numArgs, fpi);
479 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000480 };
John McCall9d125032010-01-15 18:39:57 +0000481
482 // Helper function: create a CStyleCastExpr with trivial type source info.
483 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000484 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000485 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000486 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000487 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000488 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000489}
490
Mike Stump1eb44332009-09-09 15:08:12 +0000491void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
492 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000493 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000494 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000495 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000496 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000497 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000498 // All the args are checked/rewritten. Don't call twice!
499 RewriteBlockPointerDecl(D);
500 break;
501 }
502 }
503}
504
505void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000506 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000507 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000508 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000509}
510
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000511static bool IsHeaderFile(const std::string &Filename) {
512 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000514 if (DotPos == std::string::npos) {
515 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000516 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000519 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
520 // C header: .h
521 // C++ header: .hh or .H;
522 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000523}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000524
Chris Lattner5f9e2722011-07-23 10:55:15 +0000525RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000526 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000527 bool silenceMacroWarn)
528 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
529 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000530 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000531 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000532 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000533 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
534 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000535 "rewriter doesn't support user-specified control flow semantics "
536 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000537}
538
Eli Friedmanbce831b2009-05-18 22:29:17 +0000539ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000540 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000541 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000542 const LangOptions &LOpts,
543 bool SilenceRewriteMacroWarning) {
544 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000545}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000546
Steve Naroffb29b4272008-04-14 22:03:09 +0000547void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000548 Context = &context;
549 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000550 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000551 MsgSendFunctionDecl = 0;
552 MsgSendSuperFunctionDecl = 0;
553 MsgSendStretFunctionDecl = 0;
554 MsgSendSuperStretFunctionDecl = 0;
555 MsgSendFpretFunctionDecl = 0;
556 GetClassFunctionDecl = 0;
557 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000558 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000559 SelGetUidFunctionDecl = 0;
560 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000561 ConstantStringClassReference = 0;
562 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000563 CurMethodDef = 0;
564 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000565 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000566 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000567 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000568 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000569 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000570 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000571 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000572 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000573 PropParentMap = 0;
574 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000575 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000576 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000578 // Get the ID and start/end of the main file.
579 MainFileID = SM->getMainFileID();
580 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
581 MainFileStart = MainBuf->getBufferStart();
582 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner2c78b872009-04-14 23:22:57 +0000584 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000586 // declaring objc_selector outside the parameter list removes a silly
587 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000588 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000589 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000591 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000592 Preamble += "struct objc_object *superClass; ";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000593 if (LangOpts.MicrosoftExt) {
Steve Naroffc0a123c2008-03-11 17:37:02 +0000594 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000595 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
596 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000597 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000598 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000600 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
601 Preamble += "typedef struct objc_object Protocol;\n";
602 Preamble += "#define _REWRITER_typedef_Protocol\n";
603 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000604 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000605 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
606 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
607 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000608 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000609 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000610 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000611 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000612 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000614 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000615 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000617 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000618 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000619 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000620 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000621 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
622 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000624 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
626 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
627 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
628 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
629 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000630 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000631 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000632 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
633 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
634 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000635 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
636 Preamble += "struct __objcFastEnumerationState {\n\t";
637 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000638 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000639 Preamble += "unsigned long *mutationsPtr;\n\t";
640 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000641 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000642 Preamble += "#define __FASTENUMERATIONSTATE\n";
643 Preamble += "#endif\n";
644 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
645 Preamble += "struct __NSConstantStringImpl {\n";
646 Preamble += " int *isa;\n";
647 Preamble += " int flags;\n";
648 Preamble += " char *str;\n";
649 Preamble += " long length;\n";
650 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000651 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
652 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
653 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000654 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000655 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000656 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
657 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000658 // Blocks preamble.
659 Preamble += "#ifndef BLOCK_IMPL\n";
660 Preamble += "#define BLOCK_IMPL\n";
661 Preamble += "struct __block_impl {\n";
662 Preamble += " void *isa;\n";
663 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000664 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000665 Preamble += " void *FuncPtr;\n";
666 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000667 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000668 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000669 Preamble += "extern \"C\" __declspec(dllexport) "
670 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000671 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
672 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
673 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
674 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000675 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
676 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000677 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
678 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
679 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000680 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000681 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000682 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
683 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000684 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000685 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000686 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000687 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000688 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000689 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000690 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000691 Preamble += "#define __weak\n";
692 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000693 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
694 // as this avoids warning in any 64bit/32bit compilation model.
695 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000696}
697
698
Chris Lattnerf04da132007-10-24 17:06:59 +0000699//===----------------------------------------------------------------------===//
700// Top Level Driver Code
701//===----------------------------------------------------------------------===//
702
Chris Lattner682bf922009-03-29 16:50:03 +0000703void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000704 if (Diags.hasErrorOccurred())
705 return;
706
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000707 // Two cases: either the decl could be in the main file, or it could be in a
708 // #included file. If the former, rewrite it now. If the later, check to see
709 // if we rewrote the #include/#import.
710 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000711 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000713 // If this is for a builtin, ignore it.
714 if (Loc.isInvalid()) return;
715
Steve Naroffebf2b562007-10-23 23:50:29 +0000716 // Look for built-in declarations that we need to refer during the rewrite.
717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000718 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000719 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000720 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000721 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000722 ConstantStringClassReference = FVD;
723 return;
724 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000725 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000726 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000727 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000728 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000729 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000730 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000731 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000733 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000734 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
735 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000736 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
737 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000738 DI != DIEnd; ) {
739 if (isa<ObjCClassDecl>((*DI))) {
740 SmallVector<Decl *, 8> DG;
741 Decl *D = (*DI);
742 SourceLocation Loc = D->getLocation();
743 while (DI != DIEnd &&
744 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
745 DG.push_back(D);
746 ++DI;
747 D = (*DI);
748 }
749 RewriteForwardClassDecl(DG);
750 continue;
751 }
Chris Lattner682bf922009-03-29 16:50:03 +0000752 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000753 ++DI;
754 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000755 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000756 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000757 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000758 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000759}
760
Chris Lattnerf04da132007-10-24 17:06:59 +0000761//===----------------------------------------------------------------------===//
762// Syntactic (non-AST) Rewriting Code
763//===----------------------------------------------------------------------===//
764
Steve Naroffb29b4272008-04-14 22:03:09 +0000765void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000766 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000767 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000768 const char *MainBufStart = MainBuf.begin();
769 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000770 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000772 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000773 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
774 if (*BufPtr == '#') {
775 if (++BufPtr == MainBufEnd)
776 return;
777 while (*BufPtr == ' ' || *BufPtr == '\t')
778 if (++BufPtr == MainBufEnd)
779 return;
780 if (!strncmp(BufPtr, "import", ImportLen)) {
781 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000782 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000783 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000784 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000785 BufPtr += ImportLen;
786 }
787 }
788 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000789}
790
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000791static std::string getIvarAccessString(ObjCIvarDecl *OID) {
792 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 std::string S;
794 S = "((struct ";
795 S += ClassDecl->getIdentifier()->getName();
796 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000797 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000798 return S;
799}
800
Steve Naroffa0876e82008-12-02 17:36:43 +0000801void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
802 ObjCImplementationDecl *IMD,
803 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000804 static bool objcGetPropertyDefined = false;
805 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000806 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000807 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000808 const char *startBuf = SM->getCharacterData(startLoc);
809 assert((*startBuf == '@') && "bogus @synthesize location");
810 const char *semiBuf = strchr(startBuf, ';');
811 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000812 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000813 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000814
815 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
816 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Steve Naroffeb0646c2008-12-02 15:48:25 +0000818 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000819 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000820 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000822 if (!OID)
823 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000824 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000825 if (!PD->getGetterMethodDecl()->isDefined()) {
826 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
827 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
828 ObjCPropertyDecl::OBJC_PR_copy));
829 std::string Getr;
830 if (GenGetProperty && !objcGetPropertyDefined) {
831 objcGetPropertyDefined = true;
832 // FIXME. Is this attribute correct in all cases?
833 Getr = "\nextern \"C\" __declspec(dllimport) "
834 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000835 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000836 RewriteObjCMethodDecl(OID->getContainingInterface(),
837 PD->getGetterMethodDecl(), Getr);
838 Getr += "{ ";
839 // Synthesize an explicit cast to gain access to the ivar.
840 // See objc-act.c:objc_synthesize_new_getter() for details.
841 if (GenGetProperty) {
842 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
843 Getr += "typedef ";
844 const FunctionType *FPRetType = 0;
845 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
846 FPRetType);
847 Getr += " _TYPE";
848 if (FPRetType) {
849 Getr += ")"; // close the precedence "scope" for "*".
850
851 // Now, emit the argument types (if any).
852 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
853 Getr += "(";
854 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
855 if (i) Getr += ", ";
856 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000857 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000858 Getr += ParamStr;
859 }
860 if (FT->isVariadic()) {
861 if (FT->getNumArgs()) Getr += ", ";
862 Getr += "...";
863 }
864 Getr += ")";
865 } else
866 Getr += "()";
867 }
868 Getr += ";\n";
869 Getr += "return (_TYPE)";
870 Getr += "objc_getProperty(self, _cmd, ";
871 SynthesizeIvarOffsetComputation(OID, Getr);
872 Getr += ", 1)";
873 }
874 else
875 Getr += "return " + getIvarAccessString(OID);
876 Getr += "; }";
877 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000878 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000879
880 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000881 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Steve Naroffeb0646c2008-12-02 15:48:25 +0000883 // Generate the 'setter' function.
884 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000885 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
886 ObjCPropertyDecl::OBJC_PR_copy);
887 if (GenSetProperty && !objcSetPropertyDefined) {
888 objcSetPropertyDefined = true;
889 // FIXME. Is this attribute correct in all cases?
890 Setr = "\nextern \"C\" __declspec(dllimport) "
891 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
892 }
893
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000894 RewriteObjCMethodDecl(OID->getContainingInterface(),
895 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000896 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000897 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000898 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000899 if (GenSetProperty) {
900 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000901 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000902 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000903 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000904 Setr += ", ";
905 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
906 Setr += "0, ";
907 else
908 Setr += "1, ";
909 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
910 Setr += "1)";
911 else
912 Setr += "0)";
913 }
914 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000915 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000916 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000917 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000918 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000919 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000920}
Chris Lattner8a12c272007-10-11 18:38:32 +0000921
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000922static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
923 std::string &typedefString) {
924 typedefString += "#ifndef _REWRITER_typedef_";
925 typedefString += ForwardDecl->getNameAsString();
926 typedefString += "\n";
927 typedefString += "#define _REWRITER_typedef_";
928 typedefString += ForwardDecl->getNameAsString();
929 typedefString += "\n";
930 typedefString += "typedef struct objc_object ";
931 typedefString += ForwardDecl->getNameAsString();
932 typedefString += ";\n#endif\n";
933}
934
935void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
936 const std::string &typedefString) {
937 SourceLocation startLoc = ClassDecl->getLocation();
938 const char *startBuf = SM->getCharacterData(startLoc);
939 const char *semiPtr = strchr(startBuf, ';');
940 // Replace the @class with typedefs corresponding to the classes.
941 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
942}
943
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000944void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000945 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000946 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
947 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
948 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
949 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000950 // Translate to typedef's that forward reference structs with the same name
951 // as the class. As a convenience, we include the original declaration
952 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000953 typedefString += "// @class ";
954 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000955 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000956 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000957 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000958 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000959 DeclGroupRef::iterator I = D.begin();
960 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
961}
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000963void RewriteObjC::RewriteForwardClassDecl(
964 const llvm::SmallVector<Decl*, 8> &D) {
965 std::string typedefString;
966 for (unsigned i = 0; i < D.size(); i++) {
967 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
968 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
969 if (i == 0) {
970 typedefString += "// @class ";
971 typedefString += ForwardDecl->getNameAsString();
972 typedefString += ";\n";
973 }
974 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
975 }
976 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000977}
978
Steve Naroffb29b4272008-04-14 22:03:09 +0000979void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000980 // When method is a synthesized one, such as a getter/setter there is
981 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000982 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000983 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000984 SourceLocation LocStart = Method->getLocStart();
985 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chandler Carruth64211622011-07-25 21:09:52 +0000987 if (SM->getExpansionLineNumber(LocEnd) >
988 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000989 InsertText(LocStart, "#if 0\n");
990 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000991 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000992 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000993 }
994}
995
Mike Stump1eb44332009-09-09 15:08:12 +0000996void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000997 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +00001000 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001001}
1002
Steve Naroffb29b4272008-04-14 22:03:09 +00001003void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +00001004 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Steve Naroff423cb562007-10-30 13:30:57 +00001006 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001007 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001009 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1010 E = CatDecl->prop_end(); I != E; ++I)
1011 RewriteProperty(*I);
1012
Mike Stump1eb44332009-09-09 15:08:12 +00001013 for (ObjCCategoryDecl::instmeth_iterator
1014 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001015 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001016 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001017 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001018 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001019 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001020 RewriteMethodDeclaration(*I);
1021
Steve Naroff423cb562007-10-30 13:30:57 +00001022 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001023 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1024 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001025}
1026
Steve Naroffb29b4272008-04-14 22:03:09 +00001027void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001028 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Steve Naroff752d6ef2007-10-30 16:42:30 +00001030 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001031 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001032
1033 for (ObjCProtocolDecl::instmeth_iterator
1034 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001035 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001036 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001037 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001038 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001039 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001040 RewriteMethodDeclaration(*I);
1041
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001042 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1043 E = PDecl->prop_end(); I != E; ++I)
1044 RewriteProperty(*I);
1045
Steve Naroff752d6ef2007-10-30 16:42:30 +00001046 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001047 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001048 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001049
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001050 // Must comment out @optional/@required
1051 const char *startBuf = SM->getCharacterData(LocStart);
1052 const char *endBuf = SM->getCharacterData(LocEnd);
1053 for (const char *p = startBuf; p < endBuf; p++) {
1054 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001055 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001056 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001058 }
1059 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001060 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001061 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001063 }
1064 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001065}
1066
Steve Naroffb29b4272008-04-14 22:03:09 +00001067void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001068 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001069 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001070 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001071 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001072 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001073}
1074
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001075void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1076 const FunctionType *&FPRetType) {
1077 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001078 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001079 else if (T->isFunctionPointerType() ||
1080 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001081 // needs special handling, since pointer-to-functions have special
1082 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001083 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001084 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001085 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001086 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001087 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001088 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001089 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001090 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001091 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001092 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001093 }
1094 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001095 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001096}
1097
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001098void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1099 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001100 std::string &ResultStr) {
1101 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1102 const FunctionType *FPRetType = 0;
1103 ResultStr += "\nstatic ";
1104 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001105 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001107 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001108 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001110 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001111 NameStr += "_I_";
1112 else
1113 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001115 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001116 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001117
1118 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001119 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001121 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001122 }
Mike Stump1eb44332009-09-09 15:08:12 +00001123 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001124 {
1125 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001126 int len = selString.size();
1127 for (int i = 0; i < len; i++)
1128 if (selString[i] == ':')
1129 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001130 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001131 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001132 // Remember this name for metadata emission
1133 MethodInternalNames[OMD] = NameStr;
1134 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001136 // Rewrite arguments
1137 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001139 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001140 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001141 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001142 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001143 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001144 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001145 ResultStr += "struct ";
1146 }
1147 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001148 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001149 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 }
1151 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001152 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001153 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001155 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001156 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001157 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001159 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001160 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1161 E = OMD->param_end(); PI != E; ++PI) {
1162 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001164 if (PDecl->getType()->isObjCQualifiedIdType()) {
1165 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001166 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001167 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001168 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001169 QualType QT = PDecl->getType();
1170 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1171 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001172 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001173 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001174 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001175 ResultStr += Name;
1176 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001177 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001178 if (OMD->isVariadic())
1179 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001180 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Steve Naroff76e429d2008-07-16 14:40:40 +00001182 if (FPRetType) {
1183 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Steve Naroff76e429d2008-07-16 14:40:40 +00001185 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001186 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001187 ResultStr += "(";
1188 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1189 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001190 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001191 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001192 ResultStr += ParamStr;
1193 }
1194 if (FT->isVariadic()) {
1195 if (FT->getNumArgs()) ResultStr += ", ";
1196 ResultStr += "...";
1197 }
1198 ResultStr += ")";
1199 } else {
1200 ResultStr += "()";
1201 }
1202 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001203}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001204void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001205 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1206 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001208 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001210 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001211 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1212 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001213 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001214 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001215 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001216 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001217 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001218 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001219
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001220 const char *startBuf = SM->getCharacterData(LocStart);
1221 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001222 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001225 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001226 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1227 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001228 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001229 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001230 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001231 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001232 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001233 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001235 const char *startBuf = SM->getCharacterData(LocStart);
1236 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001237 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001238 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001239 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001240 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001241 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001242 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001243 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001244 }
1245
Benjamin Kramerd999b372010-02-14 14:14:16 +00001246 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001247}
1248
Steve Naroffb29b4272008-04-14 22:03:09 +00001249void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001250 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001251 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001252 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001253 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001254 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001255 ResultStr += "\n";
1256 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001257 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001258 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001259 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001260 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001261 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001262 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001263 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001264 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001265 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
1267 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001268 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001269 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001270 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001271 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001272 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001273 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001274 for (ObjCInterfaceDecl::classmeth_iterator
1275 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001276 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001277 RewriteMethodDeclaration(*I);
1278
Steve Naroff2feac5e2007-10-30 03:43:13 +00001279 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001280 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1281 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001282}
1283
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001284Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001285 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001286 ObjCMethodDecl *OMD = 0;
1287 QualType Ty;
1288 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001289 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001290 bool Super = false;
1291 QualType SuperTy;
1292 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001293 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001294 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001295 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001296 if (ObjCPropertyRefExpr *PropRefExpr =
1297 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001298 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001299 if (PropRefExpr->isExplicitProperty()) {
1300 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1301 OMD = PDecl->getSetterMethodDecl();
1302 Ty = PDecl->getType();
1303 Sel = PDecl->getSetterName();
1304 } else {
1305 OMD = PropRefExpr->getImplicitPropertySetter();
1306 Sel = OMD->getSelector();
1307 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001308 }
John McCall12f78a62010-12-02 01:19:52 +00001309 Super = PropRefExpr->isSuperReceiver();
1310 if (!Super) {
1311 Receiver = PropRefExpr->getBase();
1312 } else {
1313 SuperTy = PropRefExpr->getSuperReceiverType();
1314 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001315 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001316 }
1317
1318 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001320 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001321 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001322 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001323 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001324 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001325 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001326 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001327 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001328 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001329 Sel, SelectorLoc, OMD,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001330 newStmt,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001331 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001332 else {
1333 // FIXME. Refactor this into common code with that in
1334 // RewritePropertyOrImplicitGetter
1335 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1336 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1337 if (PropGetters[Exp])
1338 // This allows us to handle chain/nested property/implicit getters.
1339 Receiver = PropGetters[Exp];
1340
Douglas Gregor04badcf2010-04-21 00:45:42 +00001341 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001342 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001343 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001344 /*FIXME: */SourceLocation(),
1345 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001346 Sel, SelectorLoc, OMD,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001347 newStmt,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001348 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001349 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001350 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Steve Naroffc77a6362008-12-04 16:24:46 +00001352 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001353 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001354 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001355 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1356 // to things that stay around.
1357 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001358 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001359}
1360
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001361Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1362 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001363 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001364 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001365 ObjCMethodDecl *OMD = 0;
1366 QualType Ty;
1367 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001368 bool Super = false;
1369 QualType SuperTy;
1370 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001371 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001372 if (ObjCPropertyRefExpr *PropRefExpr =
1373 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001374 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001375 if (PropRefExpr->isExplicitProperty()) {
1376 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1377 OMD = PDecl->getGetterMethodDecl();
1378 Ty = PDecl->getType();
1379 Sel = PDecl->getGetterName();
1380 } else {
1381 OMD = PropRefExpr->getImplicitPropertyGetter();
1382 Sel = OMD->getSelector();
1383 Ty = PropRefExpr->getType();
1384 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001385 Super = PropRefExpr->isSuperReceiver();
1386 if (!Super)
1387 Receiver = PropRefExpr->getBase();
1388 else {
John McCall12f78a62010-12-02 01:19:52 +00001389 SuperTy = PropRefExpr->getSuperReceiverType();
1390 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001391 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001392 }
1393
1394 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1395
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001396 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001397 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001398 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001399 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001400 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001401 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001402 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001403 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001404 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001405 Sel, SelectorLoc, OMD,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001406 ArrayRef<Expr*>(),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001407 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001408 else {
1409 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1410 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1411 if (PropGetters[Exp])
1412 // This allows us to handle chain/nested property/implicit getters.
1413 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001414 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001415 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001416 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001417 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001418 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001419 Sel, SelectorLoc, OMD,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001420 ArrayRef<Expr*>(),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001421 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001422 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001423
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001424 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1425 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001426
1427 if (!PropParentMap)
1428 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001429 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001430 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001431 ImplicitCastExpr*ICE=0;
1432 if (Parent)
1433 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1434 assert((ICE->getCastKind() == CK_GetObjCProperty)
1435 && "RewritePropertyOrImplicitGetter");
1436 Parent = PropParentMap->getParent(Parent);
1437 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1438 }
1439 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001440 // We stash away the ReplacingStmt since actually doing the
1441 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001442 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001443 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1444 // to things that stay around.
1445 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001446 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001447 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001448 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001449 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001450 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1451 // to things that stay around.
1452 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001453 return ReplacingStmt;
1454 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001455}
1456
Mike Stump1eb44332009-09-09 15:08:12 +00001457Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001458 SourceLocation OrigStart,
1459 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001460 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001461 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001462 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001463 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001464 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001465 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001466 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001467 // lookup which class implements the instance variable.
1468 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001469 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001470 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001471 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Steve Narofff0757612008-05-08 17:52:16 +00001473 // Synthesize an explicit cast to gain access to the ivar.
1474 std::string RecName = clsDeclared->getIdentifier()->getName();
1475 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001476 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001477 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001478 SourceLocation(), SourceLocation(),
1479 II);
Steve Narofff0757612008-05-08 17:52:16 +00001480 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1481 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001482 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001483 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001484 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001485 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001486 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001487 IV->getBase()->getLocEnd(),
1488 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001489 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001490 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001491 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001492 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001493 IV->getLocation(),
1494 D->getType(),
1495 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001496 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001497 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001498 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001499 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001500 // Cannot delete IV->getBase(), since PE points to it.
1501 // Replace the old base with the cast. This is important when doing
1502 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001503 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001504 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001505 }
Steve Naroff84472a82008-04-18 21:55:08 +00001506 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001507 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Steve Naroff9f525972008-05-06 23:20:07 +00001509 // Explicit ivar refs need to have a cast inserted.
1510 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001511 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001512 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001513 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001514 // lookup which class implements the instance variable.
1515 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001516 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001517 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001518 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Steve Naroff9f525972008-05-06 23:20:07 +00001520 // Synthesize an explicit cast to gain access to the ivar.
1521 std::string RecName = clsDeclared->getIdentifier()->getName();
1522 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001523 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001524 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001525 SourceLocation(), SourceLocation(),
1526 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001527 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1528 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001529 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001530 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001531 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001532 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001533 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001534 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001535 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001536 // Cannot delete IV->getBase(), since PE points to it.
1537 // Replace the old base with the cast. This is important when doing
1538 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001539 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001540 return IV;
1541 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001542 }
Steve Naroff84472a82008-04-18 21:55:08 +00001543 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001544}
1545
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001546Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001547 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001548 if (*CI) {
1549 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1550 if (newStmt)
1551 *CI = newStmt;
1552 }
1553 }
1554 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1555 SourceRange OrigStmtRange = S->getSourceRange();
1556 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1557 replaced);
1558 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001559 }
1560 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1561 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1562 return newStmt;
1563 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001564 return S;
1565}
1566
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567/// SynthCountByEnumWithState - To print:
1568/// ((unsigned int (*)
1569/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001570/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001571/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001572/// "countByEnumeratingWithState:objects:count:"),
1573/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001574/// (id *)items, (unsigned int)16)
1575///
Steve Naroffb29b4272008-04-14 22:03:09 +00001576void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001577 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1578 "id *, unsigned int))(void *)objc_msgSend)";
1579 buf += "\n\t\t";
1580 buf += "((id)l_collection,\n\t\t";
1581 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1582 buf += "\n\t\t";
1583 buf += "&enumState, "
1584 "(id *)items, (unsigned int)16)";
1585}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001586
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001587/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1588/// statement to exit to its outer synthesized loop.
1589///
Steve Naroffb29b4272008-04-14 22:03:09 +00001590Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001591 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1592 return S;
1593 // replace break with goto __break_label
1594 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001596 SourceLocation startLoc = S->getLocStart();
1597 buf = "goto __break_label_";
1598 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001599 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001600
1601 return 0;
1602}
1603
1604/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1605/// statement to continue with its inner synthesized loop.
1606///
Steve Naroffb29b4272008-04-14 22:03:09 +00001607Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001608 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1609 return S;
1610 // replace continue with goto __continue_label
1611 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001613 SourceLocation startLoc = S->getLocStart();
1614 buf = "goto __continue_label_";
1615 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001616 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001618 return 0;
1619}
1620
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001621/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001622/// It rewrites:
1623/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001625/// Into:
1626/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001627/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001628/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001629/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001630/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001631/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001632/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001633/// if (limit) {
1634/// unsigned long startMutations = *enumState.mutationsPtr;
1635/// do {
1636/// unsigned long counter = 0;
1637/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001638/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001639/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001640/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001641/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001642/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001643/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001644/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001645/// objects:items count:16]);
1646/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001647/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001648/// }
1649/// else
1650/// elem = nil;
1651/// }
1652///
Steve Naroffb29b4272008-04-14 22:03:09 +00001653Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001654 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001655 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001656 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001657 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001658 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001659 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001661 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001662 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001663 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001664 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001665 std::string buf;
1666 buf = "\n{\n\t";
1667 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1668 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001669 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001670 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001671 if (ElementType->isObjCQualifiedIdType() ||
1672 ElementType->isObjCQualifiedInterfaceType())
1673 // Simply use 'id' for all qualified types.
1674 elementTypeAsString = "id";
1675 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001676 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001677 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001678 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001679 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001680 buf += elementName;
1681 buf += ";\n\t";
1682 }
Chris Lattner06767512008-04-08 05:52:18 +00001683 else {
1684 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001685 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001686 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1687 if (VD->getType()->isObjCQualifiedIdType() ||
1688 VD->getType()->isObjCQualifiedInterfaceType())
1689 // Simply use 'id' for all qualified types.
1690 elementTypeAsString = "id";
1691 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001692 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001693 }
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001695 // struct __objcFastEnumerationState enumState = { 0 };
1696 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1697 // id items[16];
1698 buf += "id items[16];\n\t";
1699 // id l_collection = (id)
1700 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001701 // Find start location of 'collection' the hard way!
1702 const char *startCollectionBuf = startBuf;
1703 startCollectionBuf += 3; // skip 'for'
1704 startCollectionBuf = strchr(startCollectionBuf, '(');
1705 startCollectionBuf++; // skip '('
1706 // find 'in' and skip it.
1707 while (*startCollectionBuf != ' ' ||
1708 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1709 (*(startCollectionBuf+3) != ' ' &&
1710 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1711 startCollectionBuf++;
1712 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001713
1714 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001715 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001716 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001717 SourceLocation rightParenLoc = S->getRParenLoc();
1718 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001719 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001720 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001722 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1723 // objects:items count:16];
1724 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001725 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001726 // ((unsigned int (*)
1727 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001728 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001729 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001730 // "countByEnumeratingWithState:objects:count:"),
1731 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001732 // (id *)items, (unsigned int)16);
1733 buf += "unsigned long limit =\n\t\t";
1734 SynthCountByEnumWithState(buf);
1735 buf += ";\n\t";
1736 /// if (limit) {
1737 /// unsigned long startMutations = *enumState.mutationsPtr;
1738 /// do {
1739 /// unsigned long counter = 0;
1740 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001741 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001742 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001743 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001744 buf += "if (limit) {\n\t";
1745 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1746 buf += "do {\n\t\t";
1747 buf += "unsigned long counter = 0;\n\t\t";
1748 buf += "do {\n\t\t\t";
1749 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1750 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1751 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001752 buf += " = (";
1753 buf += elementTypeAsString;
1754 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001755 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001756 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001758 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001759 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001760 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001761 /// objects:items count:16]);
1762 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001763 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001764 /// }
1765 /// else
1766 /// elem = nil;
1767 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001768 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001769 buf = ";\n\t";
1770 buf += "__continue_label_";
1771 buf += utostr(ObjCBcLabelNo.back());
1772 buf += ": ;";
1773 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001774 buf += "} while (counter < limit);\n\t";
1775 buf += "} while (limit = ";
1776 SynthCountByEnumWithState(buf);
1777 buf += ");\n\t";
1778 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001779 buf += " = ((";
1780 buf += elementTypeAsString;
1781 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001782 buf += "__break_label_";
1783 buf += utostr(ObjCBcLabelNo.back());
1784 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001785 buf += "}\n\t";
1786 buf += "else\n\t\t";
1787 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001788 buf += " = ((";
1789 buf += elementTypeAsString;
1790 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001791 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001793 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001794 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001795 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001796 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001797 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001798 } else {
1799 /* Need to treat single statements specially. For example:
1800 *
1801 * for (A *a in b) if (stuff()) break;
1802 * for (A *a in b) xxxyy;
1803 *
1804 * The following code simply scans ahead to the semi to find the actual end.
1805 */
1806 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1807 const char *semiBuf = strchr(stmtBuf, ';');
1808 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001809 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001810 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001811 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001812 Stmts.pop_back();
1813 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001814 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001815}
1816
Mike Stump1eb44332009-09-09 15:08:12 +00001817/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001818/// This routine rewrites @synchronized(expr) stmt;
1819/// into:
1820/// objc_sync_enter(expr);
1821/// @try stmt @finally { objc_sync_exit(expr); }
1822///
Steve Naroffb29b4272008-04-14 22:03:09 +00001823Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001824 // Get the start location and compute the semi location.
1825 SourceLocation startLoc = S->getLocStart();
1826 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001828 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001829
1830 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001831 buf = "objc_sync_enter((id)";
1832 const char *lparenBuf = startBuf;
1833 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001834 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001835 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1836 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001837 // been rewritten! (which implies the SourceLocation's are invalid).
1838 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001839 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001840 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001841 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001842 buf = ");\n";
1843 // declare a new scope with two variables, _stack and _rethrow.
1844 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1845 buf += "int buf[18/*32-bit i386*/];\n";
1846 buf += "char *pointers[4];} _stack;\n";
1847 buf += "id volatile _rethrow = 0;\n";
1848 buf += "objc_exception_try_enter(&_stack);\n";
1849 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001850 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001851 startLoc = S->getSynchBody()->getLocEnd();
1852 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Steve Naroffc7089f12008-08-19 13:04:19 +00001854 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001855 SourceLocation lastCurlyLoc = startLoc;
1856 buf = "}\nelse {\n";
1857 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001858 buf += "}\n";
1859 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001860 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001861
1862 std::string syncBuf;
1863 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001864
1865 Expr *syncExpr = S->getSynchExpr();
1866 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1867 ? CK_BitCast :
1868 syncExpr->getType()->isBlockPointerType()
1869 ? CK_BlockPointerToObjCPointerCast
1870 : CK_CPointerToObjCPointerCast;
1871 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1872 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001873 std::string syncExprBufS;
1874 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001875 syncExpr->printPretty(syncExprBuf, *Context, 0,
1876 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001877 syncBuf += syncExprBuf.str();
1878 syncBuf += ");";
1879
1880 buf += syncBuf;
1881 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001882 buf += "}\n";
1883 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Benjamin Kramerd999b372010-02-14 14:14:16 +00001885 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001886
1887 bool hasReturns = false;
1888 HasReturnStmts(S->getSynchBody(), hasReturns);
1889 if (hasReturns)
1890 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1891
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001892 return 0;
1893}
1894
Steve Naroffb85e77a2009-12-05 21:43:12 +00001895void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1896{
Steve Naroff8c565152008-12-05 17:03:39 +00001897 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001898 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001899 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001900 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001901
Steve Naroffb85e77a2009-12-05 21:43:12 +00001902 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001903 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001904 TryFinallyContainsReturnDiag);
1905 }
1906 return;
1907}
1908
Steve Naroffb85e77a2009-12-05 21:43:12 +00001909void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1910{
1911 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001912 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001913 if (*CI)
1914 HasReturnStmts(*CI, hasReturns);
1915
1916 if (isa<ReturnStmt>(S))
1917 hasReturns = true;
1918 return;
1919}
1920
1921void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1922 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001923 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001924 if (*CI) {
1925 RewriteTryReturnStmts(*CI);
1926 }
1927 if (isa<ReturnStmt>(S)) {
1928 SourceLocation startLoc = S->getLocStart();
1929 const char *startBuf = SM->getCharacterData(startLoc);
1930
1931 const char *semiBuf = strchr(startBuf, ';');
1932 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001933 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001934
1935 std::string buf;
1936 buf = "{ objc_exception_try_exit(&_stack); return";
1937
Benjamin Kramerd999b372010-02-14 14:14:16 +00001938 ReplaceText(startLoc, 6, buf);
1939 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001940 }
1941 return;
1942}
1943
1944void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1945 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001946 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001947 if (*CI) {
1948 RewriteSyncReturnStmts(*CI, syncExitBuf);
1949 }
1950 if (isa<ReturnStmt>(S)) {
1951 SourceLocation startLoc = S->getLocStart();
1952 const char *startBuf = SM->getCharacterData(startLoc);
1953
1954 const char *semiBuf = strchr(startBuf, ';');
1955 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001956 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001957
1958 std::string buf;
1959 buf = "{ objc_exception_try_exit(&_stack);";
1960 buf += syncExitBuf;
1961 buf += " return";
1962
Benjamin Kramerd999b372010-02-14 14:14:16 +00001963 ReplaceText(startLoc, 6, buf);
1964 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001965 }
1966 return;
1967}
1968
Steve Naroffb29b4272008-04-14 22:03:09 +00001969Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001970 // Get the start location and compute the semi location.
1971 SourceLocation startLoc = S->getLocStart();
1972 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Steve Naroff75730982007-11-07 04:08:17 +00001974 assert((*startBuf == '@') && "bogus @try location");
1975
1976 std::string buf;
1977 // declare a new scope with two variables, _stack and _rethrow.
1978 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1979 buf += "int buf[18/*32-bit i386*/];\n";
1980 buf += "char *pointers[4];} _stack;\n";
1981 buf += "id volatile _rethrow = 0;\n";
1982 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001983 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001984
Benjamin Kramerd999b372010-02-14 14:14:16 +00001985 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Steve Naroff75730982007-11-07 04:08:17 +00001987 startLoc = S->getTryBody()->getLocEnd();
1988 startBuf = SM->getCharacterData(startLoc);
1989
1990 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Steve Naroff75730982007-11-07 04:08:17 +00001992 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001993 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001994 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001995 buf = " /* @catch begin */ else {\n";
1996 buf += " id _caught = objc_exception_extract(&_stack);\n";
1997 buf += " objc_exception_try_enter (&_stack);\n";
1998 buf += " if (_setjmp(_stack.buf))\n";
1999 buf += " _rethrow = objc_exception_extract(&_stack);\n";
2000 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Benjamin Kramerd999b372010-02-14 14:14:16 +00002002 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00002003 } else { /* no catch list */
2004 buf = "}\nelse {\n";
2005 buf += " _rethrow = objc_exception_extract(&_stack);\n";
2006 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002007 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00002008 }
Steve Naroff75730982007-11-07 04:08:17 +00002009 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002010 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2011 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00002012 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00002013
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002014 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00002015 buf = "if ("; // we are generating code for the first catch clause
2016 else
2017 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002018 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00002019 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Steve Naroff75730982007-11-07 04:08:17 +00002021 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Steve Naroff75730982007-11-07 04:08:17 +00002023 const char *lParenLoc = strchr(startBuf, '(');
2024
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002025 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00002026 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002027 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00002028 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2029 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002030 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00002031 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002032 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Steve Naroffe12e6922008-02-01 20:02:07 +00002034 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002035 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002036 } else if (catchDecl) {
2037 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002038 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002039 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002040 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002041 } else if (const ObjCObjectPointerType *Ptr =
2042 t->getAs<ObjCObjectPointerType>()) {
2043 // Should be a pointer to a class.
2044 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2045 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002046 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002047 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002048 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002049 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002050 }
2051 }
2052 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002053 lastCatchBody = Catch->getCatchBody();
2054 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002055 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2056 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2057 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2058 assert((*rParenBuf == ')') && "bogus @catch paren location");
2059 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Mike Stump1eb44332009-09-09 15:08:12 +00002061 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002062 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002063 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002064 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00002065 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002066 }
Steve Naroff75730982007-11-07 04:08:17 +00002067 }
2068 // Complete the catch list...
2069 if (lastCatchBody) {
2070 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002071 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2072 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Steve Naroff378f47a2008-09-11 15:29:03 +00002074 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002075 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00002076 buf = "} /* last catch end */\n";
2077 buf += "else {\n";
2078 buf += " _rethrow = _caught;\n";
2079 buf += " objc_exception_try_exit(&_stack);\n";
2080 buf += "} } /* @catch end */\n";
2081 if (!S->getFinallyStmt())
2082 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002083 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Steve Naroff75730982007-11-07 04:08:17 +00002085 // Set lastCurlyLoc
2086 lastCurlyLoc = lastCatchBody->getLocEnd();
2087 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002088 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002089 startLoc = finalStmt->getLocStart();
2090 startBuf = SM->getCharacterData(startLoc);
2091 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Benjamin Kramerd999b372010-02-14 14:14:16 +00002093 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Steve Naroff75730982007-11-07 04:08:17 +00002095 Stmt *body = finalStmt->getFinallyBody();
2096 SourceLocation startLoc = body->getLocStart();
2097 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002098 assert(*SM->getCharacterData(startLoc) == '{' &&
2099 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002100 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002101 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002103 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002104 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002105 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002106 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Steve Naroff75730982007-11-07 04:08:17 +00002108 // Set lastCurlyLoc
2109 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Steve Naroff8c565152008-12-05 17:03:39 +00002111 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002112 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002113 } else { /* no finally clause - make sure we synthesize an implicit one */
2114 buf = "{ /* implicit finally clause */\n";
2115 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2116 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2117 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002118 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002119
2120 // Now check for any return/continue/go statements within the @try.
2121 // The implicit finally clause won't called if the @try contains any
2122 // jump statements.
2123 bool hasReturns = false;
2124 HasReturnStmts(S->getTryBody(), hasReturns);
2125 if (hasReturns)
2126 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002127 }
2128 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002129 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002130 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002131 return 0;
2132}
2133
Mike Stump1eb44332009-09-09 15:08:12 +00002134// This can't be done with ReplaceStmt(S, ThrowExpr), since
2135// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002136// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002137Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002138 // Get the start location and compute the semi location.
2139 SourceLocation startLoc = S->getLocStart();
2140 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Steve Naroff2bd03922007-11-07 15:32:26 +00002142 assert((*startBuf == '@') && "bogus @throw location");
2143
2144 std::string buf;
2145 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002146 if (S->getThrowExpr())
2147 buf = "objc_exception_throw(";
2148 else // add an implicit argument
2149 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002151 // handle "@ throw" correctly.
2152 const char *wBuf = strchr(startBuf, 'w');
2153 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002154 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Steve Naroff2bd03922007-11-07 15:32:26 +00002156 const char *semiBuf = strchr(startBuf, ';');
2157 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002158 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002159 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002160 return 0;
2161}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002162
Steve Naroffb29b4272008-04-14 22:03:09 +00002163Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002164 // Create a new string expression.
2165 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002166 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002167 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002168 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002169 StringLiteral::Ascii, false,
2170 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002171 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Chris Lattner07506182007-11-30 22:53:43 +00002173 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002174 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002175 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002176}
2177
Steve Naroffb29b4272008-04-14 22:03:09 +00002178Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002179 if (!SelGetUidFunctionDecl)
2180 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002181 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2182 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002183 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002184 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002185 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002186 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002187 StringLiteral::Ascii, false,
2188 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002189 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2190 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002191 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002192 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002193 return SelExp;
2194}
2195
Steve Naroffb29b4272008-04-14 22:03:09 +00002196CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002197 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2198 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002199 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002200 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Steve Naroffebf2b562007-10-23 23:50:29 +00002202 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002203 DeclRefExpr *DRE =
2204 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Steve Naroffebf2b562007-10-23 23:50:29 +00002206 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002207 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002208 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002209 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002210 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
John McCall183700f2009-09-21 23:43:11 +00002212 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002214 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002215 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002216 FT->getCallResultType(*Context),
2217 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002218 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002219}
2220
Steve Naroffd5255f52007-11-01 13:24:47 +00002221static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2222 const char *&startRef, const char *&endRef) {
2223 while (startBuf < endBuf) {
2224 if (*startBuf == '<')
2225 startRef = startBuf; // mark the start.
2226 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002227 if (startRef && *startRef == '<') {
2228 endRef = startBuf; // mark the end.
2229 return true;
2230 }
2231 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002232 }
2233 startBuf++;
2234 }
2235 return false;
2236}
2237
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002238static void scanToNextArgument(const char *&argRef) {
2239 int angle = 0;
2240 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2241 if (*argRef == '<')
2242 angle++;
2243 else if (*argRef == '>')
2244 angle--;
2245 argRef++;
2246 }
2247 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2248}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002249
Steve Naroffb29b4272008-04-14 22:03:09 +00002250bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002251 if (T->isObjCQualifiedIdType())
2252 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002253 if (const PointerType *PT = T->getAs<PointerType>()) {
2254 if (PT->getPointeeType()->isObjCQualifiedIdType())
2255 return true;
2256 }
2257 if (T->isObjCObjectPointerType()) {
2258 T = T->getPointeeType();
2259 return T->isObjCQualifiedInterfaceType();
2260 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002261 if (T->isArrayType()) {
2262 QualType ElemTy = Context->getBaseElementType(T);
2263 return needToScanForQualifiers(ElemTy);
2264 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002265 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002266}
2267
Steve Naroff4f95b752008-07-29 18:15:38 +00002268void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2269 QualType Type = E->getType();
2270 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002271 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Steve Naroffcda658e2008-11-19 21:15:47 +00002273 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2274 Loc = ECE->getLParenLoc();
2275 EndLoc = ECE->getRParenLoc();
2276 } else {
2277 Loc = E->getLocStart();
2278 EndLoc = E->getLocEnd();
2279 }
2280 // This will defend against trying to rewrite synthesized expressions.
2281 if (Loc.isInvalid() || EndLoc.isInvalid())
2282 return;
2283
Steve Naroff4f95b752008-07-29 18:15:38 +00002284 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002285 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002286 const char *startRef = 0, *endRef = 0;
2287 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2288 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002289 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2290 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002291 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002292 InsertText(LessLoc, "/*");
2293 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002294 }
2295 }
2296}
2297
Steve Naroffb29b4272008-04-14 22:03:09 +00002298void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002299 SourceLocation Loc;
2300 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002301 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002302 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2303 Loc = VD->getLocation();
2304 Type = VD->getType();
2305 }
2306 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2307 Loc = FD->getLocation();
2308 // Check for ObjC 'id' and class types that have been adorned with protocol
2309 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002310 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002311 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002312 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002313 if (!proto)
2314 return;
2315 Type = proto->getResultType();
2316 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002317 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2318 Loc = FD->getLocation();
2319 Type = FD->getType();
2320 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002321 else
2322 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002324 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002325 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Steve Naroffd5255f52007-11-01 13:24:47 +00002327 const char *endBuf = SM->getCharacterData(Loc);
2328 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002329 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002330 startBuf--; // scan backward (from the decl location) for return type.
2331 const char *startRef = 0, *endRef = 0;
2332 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2333 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002334 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2335 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002336 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002337 InsertText(LessLoc, "/*");
2338 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002339 }
2340 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002341 if (!proto)
2342 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002343 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002344 const char *startBuf = SM->getCharacterData(Loc);
2345 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002346 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2347 if (needToScanForQualifiers(proto->getArgType(i))) {
2348 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Steve Naroffd5255f52007-11-01 13:24:47 +00002350 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002351 // scan forward (from the decl location) for argument types.
2352 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002353 const char *startRef = 0, *endRef = 0;
2354 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2355 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002356 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002357 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002358 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002359 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002360 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002361 InsertText(LessLoc, "/*");
2362 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002363 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002364 startBuf = ++endBuf;
2365 }
2366 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002367 // If the function name is derived from a macro expansion, then the
2368 // argument buffer will not follow the name. Need to speak with Chris.
2369 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002370 startBuf++; // scan forward (from the decl location) for argument types.
2371 startBuf++;
2372 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002373 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002374}
2375
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002376void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2377 QualType QT = ND->getType();
2378 const Type* TypePtr = QT->getAs<Type>();
2379 if (!isa<TypeOfExprType>(TypePtr))
2380 return;
2381 while (isa<TypeOfExprType>(TypePtr)) {
2382 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2383 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2384 TypePtr = QT->getAs<Type>();
2385 }
2386 // FIXME. This will not work for multiple declarators; as in:
2387 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002388 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002389 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2390 const char *startBuf = SM->getCharacterData(DeclLoc);
2391 if (ND->getInit()) {
2392 std::string Name(ND->getNameAsString());
2393 TypeAsString += " " + Name + " = ";
2394 Expr *E = ND->getInit();
2395 SourceLocation startLoc;
2396 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2397 startLoc = ECE->getLParenLoc();
2398 else
2399 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002400 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002401 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002402 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002403 }
2404 else {
2405 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002406 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002407 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002408 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002409 }
2410}
2411
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002412// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002413void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002414 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002415 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002416 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002417 QualType getFuncType =
2418 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002419 SelGetUidFunctionDecl = 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 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002423 SC_Extern,
2424 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002425}
2426
Steve Naroffb29b4272008-04-14 22:03:09 +00002427void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002428 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002429 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002430 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002431 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002432 return;
2433 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002434 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002435}
2436
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002437void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002438 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002439 const char *argPtr = TypeString.c_str();
2440 if (!strchr(argPtr, '^')) {
2441 Str += TypeString;
2442 return;
2443 }
2444 while (*argPtr) {
2445 Str += (*argPtr == '^' ? '*' : *argPtr);
2446 argPtr++;
2447 }
2448}
2449
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002450// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002451void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2452 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002453 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002454 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002455 const char *argPtr = TypeString.c_str();
2456 int paren = 0;
2457 while (*argPtr) {
2458 switch (*argPtr) {
2459 case '(':
2460 Str += *argPtr;
2461 paren++;
2462 break;
2463 case ')':
2464 Str += *argPtr;
2465 paren--;
2466 break;
2467 case '^':
2468 Str += '*';
2469 if (paren == 1)
2470 Str += VD->getNameAsString();
2471 break;
2472 default:
2473 Str += *argPtr;
2474 break;
2475 }
2476 argPtr++;
2477 }
2478}
2479
2480
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002481void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2482 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2483 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2484 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2485 if (!proto)
2486 return;
2487 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002488 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002489 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002490 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002491 FdStr += "(";
2492 unsigned numArgs = proto->getNumArgs();
2493 for (unsigned i = 0; i < numArgs; i++) {
2494 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002495 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002496 if (i+1 < numArgs)
2497 FdStr += ", ";
2498 }
2499 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002500 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002501 CurFunctionDeclToDeclareForBlock = 0;
2502}
2503
Steve Naroffc0a123c2008-03-11 17:37:02 +00002504// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002505void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002506 if (SuperContructorFunctionDecl)
2507 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002508 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002509 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002510 QualType argT = Context->getObjCIdType();
2511 assert(!argT.isNull() && "Can't find 'id' type");
2512 ArgTys.push_back(argT);
2513 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002514 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2515 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002516 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002517 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002518 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002519 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002520 SC_Extern,
2521 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002522}
2523
Steve Naroff09b266e2007-10-30 23:14:51 +00002524// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002525void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002526 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002527 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002528 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002529 assert(!argT.isNull() && "Can't find 'id' type");
2530 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002531 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002532 assert(!argT.isNull() && "Can't find 'SEL' type");
2533 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002534 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2535 &ArgTys[0], ArgTys.size(),
2536 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002537 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002538 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002539 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002540 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002541 SC_Extern,
2542 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002543}
2544
Steve Naroff874e2322007-11-15 10:28:18 +00002545// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002546void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002547 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002548 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002549 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002550 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002551 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002552 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2553 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2554 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002556 assert(!argT.isNull() && "Can't find 'SEL' type");
2557 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002558 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2559 &ArgTys[0], ArgTys.size(),
2560 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002561 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002562 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002563 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002564 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002565 SC_Extern,
2566 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002567}
2568
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002569// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002570void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002571 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002572 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002573 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002574 assert(!argT.isNull() && "Can't find 'id' type");
2575 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002576 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002577 assert(!argT.isNull() && "Can't find 'SEL' type");
2578 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002579 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2580 &ArgTys[0], ArgTys.size(),
2581 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002582 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002583 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002584 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002585 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002586 SC_Extern,
2587 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002588}
2589
Mike Stump1eb44332009-09-09 15:08:12 +00002590// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002591// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002592void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002593 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002594 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002595 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002596 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002597 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002598 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002599 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2600 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2601 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002602 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002603 assert(!argT.isNull() && "Can't find 'SEL' type");
2604 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002605 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2606 &ArgTys[0], ArgTys.size(),
2607 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002608 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002609 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002610 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002611 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002612 SC_Extern,
2613 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002614}
2615
Steve Naroff1284db82008-05-08 22:02:18 +00002616// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002617void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002618 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002619 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002620 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002621 assert(!argT.isNull() && "Can't find 'id' type");
2622 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002623 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002624 assert(!argT.isNull() && "Can't find 'SEL' type");
2625 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002626 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2627 &ArgTys[0], ArgTys.size(),
2628 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002629 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002630 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002631 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002632 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002633 SC_Extern,
2634 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002635}
2636
Steve Naroff09b266e2007-10-30 23:14:51 +00002637// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002638void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002639 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002640 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002641 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002642 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2643 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002644 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002645 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002646 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002647 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002648 SC_Extern,
2649 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002650}
2651
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002652// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2653void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2654 IdentifierInfo *getSuperClassIdent =
2655 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002656 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002657 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002658 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2659 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002660 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002661 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002662 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002663 getSuperClassIdent,
2664 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002665 SC_Extern,
2666 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002667 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002668}
2669
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002670// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002671void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002672 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002673 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002674 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002675 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2676 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002677 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002678 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002679 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002680 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002681 SC_Extern,
2682 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002683}
2684
Steve Naroffb29b4272008-04-14 22:03:09 +00002685Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002686 QualType strType = getConstantStringStructType();
2687
2688 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002689
2690 std::string tmpName = InFileName;
2691 unsigned i;
2692 for (i=0; i < tmpName.length(); i++) {
2693 char c = tmpName.at(i);
2694 // replace any non alphanumeric characters with '_'.
2695 if (!isalpha(c) && (c < '0' || c > '9'))
2696 tmpName[i] = '_';
2697 }
2698 S += tmpName;
2699 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002700 S += utostr(NumObjCStringLiterals++);
2701
Steve Naroffba92b2e2008-03-27 22:29:16 +00002702 Preamble += "static __NSConstantStringImpl " + S;
2703 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2704 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002705 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002706 std::string prettyBufS;
2707 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002708 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2709 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002710 Preamble += prettyBuf.str();
2711 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002712 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002713
2714 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002715 SourceLocation(), &Context->Idents.get(S),
2716 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002717 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2718 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002719 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002720 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002721 VK_RValue, OK_Ordinary,
2722 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002723 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002724 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002725 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002726 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002727 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002728 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002729}
2730
Steve Naroff874e2322007-11-15 10:28:18 +00002731// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002732QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002733 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002734 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002735 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002736 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002737 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Steve Naroff874e2322007-11-15 10:28:18 +00002739 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002740 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002741 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002742 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002743
Steve Naroff874e2322007-11-15 10:28:18 +00002744 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002745 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002746 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002747 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002748 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002749 FieldTypes[i], 0,
2750 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002751 /*Mutable=*/false,
2752 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Douglas Gregor838db382010-02-11 01:19:42 +00002755 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002756 }
2757 return Context->getTagDeclType(SuperStructDecl);
2758}
2759
Steve Naroffb29b4272008-04-14 22:03:09 +00002760QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002761 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002762 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002763 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002764 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002765 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002767 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002768 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002769 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002770 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002771 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002772 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002773 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002774 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002775
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002776 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002777 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002778 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2779 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002780 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002781 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002782 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002783 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002784 /*Mutable=*/true,
2785 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002786 }
2787
Douglas Gregor838db382010-02-11 01:19:42 +00002788 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002789 }
2790 return Context->getTagDeclType(ConstantStringDecl);
2791}
2792
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002793Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2794 SourceLocation StartLoc,
2795 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002796 if (!SelGetUidFunctionDecl)
2797 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002798 if (!MsgSendFunctionDecl)
2799 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002800 if (!MsgSendSuperFunctionDecl)
2801 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002802 if (!MsgSendStretFunctionDecl)
2803 SynthMsgSendStretFunctionDecl();
2804 if (!MsgSendSuperStretFunctionDecl)
2805 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002806 if (!MsgSendFpretFunctionDecl)
2807 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002808 if (!GetClassFunctionDecl)
2809 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002810 if (!GetSuperClassFunctionDecl)
2811 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002812 if (!GetMetaClassFunctionDecl)
2813 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Steve Naroff874e2322007-11-15 10:28:18 +00002815 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002816 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2817 // May need to use objc_msgSend_stret() as well.
2818 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002819 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2820 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002821 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002822 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002823 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002824 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002825 }
Mike Stump1eb44332009-09-09 15:08:12 +00002826
Steve Naroff934f2762007-10-24 22:48:43 +00002827 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002828 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002829 switch (Exp->getReceiverKind()) {
2830 case ObjCMessageExpr::SuperClass: {
2831 MsgSendFlavor = MsgSendSuperFunctionDecl;
2832 if (MsgSendStretFlavor)
2833 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2834 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002835
Douglas Gregor04badcf2010-04-21 00:45:42 +00002836 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002837
Chris Lattner5f9e2722011-07-23 10:55:15 +00002838 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002839
Douglas Gregor04badcf2010-04-21 00:45:42 +00002840 // set the receiver to self, the first argument to all methods.
2841 InitExprs.push_back(
2842 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002843 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002845 Context->getObjCIdType(),
2846 VK_RValue,
2847 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002848 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002849
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002851 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852 QualType argType = Context->getPointerType(Context->CharTy);
2853 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002854 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002855 StringLiteral::Ascii, false,
2856 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002857 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2858 &ClsExprs[0],
2859 ClsExprs.size(),
2860 StartLoc,
2861 EndLoc);
2862 // (Class)objc_getClass("CurrentClass")
2863 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2864 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002865 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002866 ClsExprs.clear();
2867 ClsExprs.push_back(ArgExpr);
2868 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2869 &ClsExprs[0], ClsExprs.size(),
2870 StartLoc, EndLoc);
2871
2872 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2873 // To turn off a warning, type-cast to 'id'
2874 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2875 NoTypeInfoCStyleCastExpr(Context,
2876 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002877 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002878 // struct objc_super
2879 QualType superType = getSuperStructType();
2880 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002881
Francois Pichet62ec1f22011-09-17 17:15:52 +00002882 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002883 SynthSuperContructorFunctionDecl();
2884 // Simulate a contructor call...
2885 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002886 superType, VK_LValue,
2887 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002888 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2889 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002890 superType, VK_LValue,
2891 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002892 // The code for super is a little tricky to prevent collision with
2893 // the structure definition in the header. The rewriter has it's own
2894 // internal definition (__rw_objc_super) that is uses. This is why
2895 // we need the cast below. For example:
2896 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2897 //
John McCall2de56d12010-08-25 11:45:40 +00002898 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002899 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002900 VK_RValue, OK_Ordinary,
2901 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002902 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2903 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002904 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002905 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002906 // (struct objc_super) { <exprs from above> }
2907 InitListExpr *ILE =
2908 new (Context) InitListExpr(*Context, SourceLocation(),
2909 &InitExprs[0], InitExprs.size(),
2910 SourceLocation());
2911 TypeSourceInfo *superTInfo
2912 = Context->getTrivialTypeSourceInfo(superType);
2913 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002914 superType, VK_LValue,
2915 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002916 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002917 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002918 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002919 VK_RValue, OK_Ordinary,
2920 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002921 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002922 MsgExprs.push_back(SuperRep);
2923 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002924 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002925
2926 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002927 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002928 QualType argType = Context->getPointerType(Context->CharTy);
2929 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002930 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002931 IdentifierInfo *clsName = Class->getIdentifier();
2932 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002933 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002934 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002935 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002936 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2937 &ClsExprs[0],
2938 ClsExprs.size(),
2939 StartLoc, EndLoc);
2940 MsgExprs.push_back(Cls);
2941 break;
2942 }
2943
2944 case ObjCMessageExpr::SuperInstance:{
2945 MsgSendFlavor = MsgSendSuperFunctionDecl;
2946 if (MsgSendStretFlavor)
2947 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2948 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2949 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002950 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002951
2952 InitExprs.push_back(
2953 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002954 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002955 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002956 Context->getObjCIdType(),
2957 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002958 ); // set the 'receiver'.
2959
2960 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002961 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002962 QualType argType = Context->getPointerType(Context->CharTy);
2963 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002964 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002965 StringLiteral::Ascii, false, argType,
2966 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002967 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2968 &ClsExprs[0],
2969 ClsExprs.size(),
2970 StartLoc, EndLoc);
2971 // (Class)objc_getClass("CurrentClass")
2972 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2973 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002974 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002975 ClsExprs.clear();
2976 ClsExprs.push_back(ArgExpr);
2977 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2978 &ClsExprs[0], ClsExprs.size(),
2979 StartLoc, EndLoc);
2980
2981 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2982 // To turn off a warning, type-cast to 'id'
2983 InitExprs.push_back(
2984 // set 'super class', using class_getSuperclass().
2985 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002986 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002987 // struct objc_super
2988 QualType superType = getSuperStructType();
2989 Expr *SuperRep;
2990
Francois Pichet62ec1f22011-09-17 17:15:52 +00002991 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002992 SynthSuperContructorFunctionDecl();
2993 // Simulate a contructor call...
2994 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002995 superType, VK_LValue,
2996 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002997 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2998 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002999 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00003000 // The code for super is a little tricky to prevent collision with
3001 // the structure definition in the header. The rewriter has it's own
3002 // internal definition (__rw_objc_super) that is uses. This is why
3003 // we need the cast below. For example:
3004 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3005 //
John McCall2de56d12010-08-25 11:45:40 +00003006 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003007 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003008 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003009 SourceLocation());
3010 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3011 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00003012 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003013 } else {
3014 // (struct objc_super) { <exprs from above> }
3015 InitListExpr *ILE =
3016 new (Context) InitListExpr(*Context, SourceLocation(),
3017 &InitExprs[0], InitExprs.size(),
3018 SourceLocation());
3019 TypeSourceInfo *superTInfo
3020 = Context->getTrivialTypeSourceInfo(superType);
3021 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003022 superType, VK_RValue, ILE,
3023 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003024 }
3025 MsgExprs.push_back(SuperRep);
3026 break;
3027 }
3028
3029 case ObjCMessageExpr::Instance: {
3030 // Remove all type-casts because it may contain objc-style types; e.g.
3031 // Foo<Proto> *.
3032 Expr *recExpr = Exp->getInstanceReceiver();
3033 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3034 recExpr = CE->getSubExpr();
3035 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003036 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003037 MsgExprs.push_back(recExpr);
3038 break;
3039 }
3040 }
3041
Steve Naroffbeaf2992007-11-03 11:27:19 +00003042 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003043 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003044 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003045 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003046 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003047 StringLiteral::Ascii, false,
3048 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003049 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003050 &SelExprs[0], SelExprs.size(),
3051 StartLoc,
3052 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003053 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Steve Naroff934f2762007-10-24 22:48:43 +00003055 // Now push any user supplied arguments.
3056 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003057 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003058 // Make all implicit casts explicit...ICE comes in handy:-)
3059 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3060 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003061 QualType type = ICE->getType();
3062 if (needToScanForQualifiers(type))
3063 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003064 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003065 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003066 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003067 CastKind CK;
3068 if (SubExpr->getType()->isIntegralType(*Context) &&
3069 type->isBooleanType()) {
3070 CK = CK_IntegralToBoolean;
3071 } else if (type->isObjCObjectPointerType()) {
3072 if (SubExpr->getType()->isBlockPointerType()) {
3073 CK = CK_BlockPointerToObjCPointerCast;
3074 } else if (SubExpr->getType()->isPointerType()) {
3075 CK = CK_CPointerToObjCPointerCast;
3076 } else {
3077 CK = CK_BitCast;
3078 }
3079 } else {
3080 CK = CK_BitCast;
3081 }
3082
3083 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003084 }
3085 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003086 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003087 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003088 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003089 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003090 CastKind CK;
3091 if (userExpr->getType()->isIntegralType(*Context)) {
3092 CK = CK_IntegralToPointer;
3093 } else if (userExpr->getType()->isBlockPointerType()) {
3094 CK = CK_BlockPointerToObjCPointerCast;
3095 } else if (userExpr->getType()->isPointerType()) {
3096 CK = CK_CPointerToObjCPointerCast;
3097 } else {
3098 CK = CK_BitCast;
3099 }
John McCall9d125032010-01-15 18:39:57 +00003100 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003101 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003102 }
Mike Stump1eb44332009-09-09 15:08:12 +00003103 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003104 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003105 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3106 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003107 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003108 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003109 }
Steve Naroffab972d32007-11-04 22:37:50 +00003110 // Generate the funky cast.
3111 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003112 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003113 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003114
Steve Naroffab972d32007-11-04 22:37:50 +00003115 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003116 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3117 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3118 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003119 ArgTypes.push_back(Context->getObjCIdType());
3120 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003121 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003122 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003123 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3124 E = OMD->param_end(); PI != E; ++PI) {
3125 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003126 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003127 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003128 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003129 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003130 ArgTypes.push_back(t);
3131 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003132 returnType = Exp->getType();
3133 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003134 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003135 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003136 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003137 }
3138 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003139 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003140
Steve Naroffab972d32007-11-04 22:37:50 +00003141 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003142 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003143 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003144
Mike Stump1eb44332009-09-09 15:08:12 +00003145 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003146 // If we don't do this cast, we get the following bizarre warning/note:
3147 // xx.m:13: warning: function called through a non-compatible type
3148 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003149 cast = NoTypeInfoCStyleCastExpr(Context,
3150 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003151 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003152
Steve Naroffab972d32007-11-04 22:37:50 +00003153 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003154 QualType castType =
3155 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3156 // If we don't have a method decl, force a variadic cast.
3157 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003158 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003159 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003160 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003161
3162 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003163 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003164
John McCall183700f2009-09-21 23:43:11 +00003165 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003166 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003167 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003168 FT->getResultType(), VK_RValue,
3169 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003170 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003171 if (MsgSendStretFlavor) {
3172 // We have the method which returns a struct/union. Must also generate
3173 // call to objc_msgSend_stret and hang both varieties on a conditional
3174 // expression which dictate which one to envoke depending on size of
3175 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003176
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003177 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003178 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003179 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003180 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003181 cast = NoTypeInfoCStyleCastExpr(Context,
3182 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003183 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003184 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003185 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3186 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003187 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003188 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003189 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003190
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003191 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003192 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003193
John McCall183700f2009-09-21 23:43:11 +00003194 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003195 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003196 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003197 FT->getResultType(), VK_RValue,
3198 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003199
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003200 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003201 UnaryExprOrTypeTraitExpr *sizeofExpr =
3202 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3203 Context->getTrivialTypeSourceInfo(returnType),
3204 Context->getSizeType(), SourceLocation(),
3205 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003206 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3207 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3208 // For X86 it is more complicated and some kind of target specific routine
3209 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003210 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003211 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003212 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3213 llvm::APInt(IntSize, 8),
3214 Context->IntTy,
3215 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003216 BinaryOperator *lessThanExpr =
3217 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3218 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003219 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003220 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003221 new (Context) ConditionalOperator(lessThanExpr,
3222 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003223 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003224 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003225 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3226 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003227 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003228 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003229 return ReplacingStmt;
3230}
3231
Steve Naroffb29b4272008-04-14 22:03:09 +00003232Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003233 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3234 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Steve Naroff934f2762007-10-24 22:48:43 +00003236 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003237 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003238
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003239 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003240 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003241}
3242
Steve Naroff621edce2009-04-29 16:37:50 +00003243// typedef struct objc_object Protocol;
3244QualType RewriteObjC::getProtocolType() {
3245 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003246 TypeSourceInfo *TInfo
3247 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003248 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003249 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003250 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003251 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003252 }
3253 return Context->getTypeDeclType(ProtocolTypeDecl);
3254}
3255
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003256/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003257/// a synthesized/forward data reference (to the protocol's metadata).
3258/// The forward references (and metadata) are generated in
3259/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003260Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003261 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3262 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003263 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003264 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003265 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003266 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3267 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003268 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003269 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003270 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003271 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003272 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003273 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003274 ReplaceStmt(Exp, castExpr);
3275 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003276 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003277 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003278
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003279}
3280
Mike Stump1eb44332009-09-09 15:08:12 +00003281bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003282 const char *endBuf) {
3283 while (startBuf < endBuf) {
3284 if (*startBuf == '#') {
3285 // Skip whitespace.
3286 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3287 ;
3288 if (!strncmp(startBuf, "if", strlen("if")) ||
3289 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3290 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3291 !strncmp(startBuf, "define", strlen("define")) ||
3292 !strncmp(startBuf, "undef", strlen("undef")) ||
3293 !strncmp(startBuf, "else", strlen("else")) ||
3294 !strncmp(startBuf, "elif", strlen("elif")) ||
3295 !strncmp(startBuf, "endif", strlen("endif")) ||
3296 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3297 !strncmp(startBuf, "include", strlen("include")) ||
3298 !strncmp(startBuf, "import", strlen("import")) ||
3299 !strncmp(startBuf, "include_next", strlen("include_next")))
3300 return true;
3301 }
3302 startBuf++;
3303 }
3304 return false;
3305}
3306
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003307/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003308/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003309void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003310 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003311 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003312 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003313 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003314 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003315 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003316 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003317 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003318 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003319 SourceLocation LocStart = CDecl->getLocStart();
3320 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Steve Narofffea763e82007-11-14 19:25:57 +00003322 const char *startBuf = SM->getCharacterData(LocStart);
3323 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003325 // If no ivars and no root or if its root, directly or indirectly,
3326 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003327 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3328 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003329 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003330 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003331 return;
3332 }
Mike Stump1eb44332009-09-09 15:08:12 +00003333
3334 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003335 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003336 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003337 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003338 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003339 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003340
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003341 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003342 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003343 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003344 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003345 // If the buffer contains preprocessor directives, we do more fine-grained
3346 // rewrites. This is intended to fix code that looks like (which occurs in
3347 // NSURL.h, for example):
3348 //
3349 // #ifdef XYZ
3350 // @interface Foo : NSObject
3351 // #else
3352 // @interface FooBar : NSObject
3353 // #endif
3354 // {
3355 // int i;
3356 // }
3357 // @end
3358 //
3359 // This clause is segregated to avoid breaking the common case.
3360 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003361 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003362 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003363 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003364 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003365
Chris Lattnercafeb352009-02-20 18:18:36 +00003366 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003367 // advance to the end of the referenced protocols.
3368 while (endHeader < cursor && *endHeader != '>') endHeader++;
3369 endHeader++;
3370 }
3371 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003372 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003373 } else {
3374 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003375 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003376 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003377 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003378 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003379 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003380 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003381 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003382 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003383
Steve Narofffea763e82007-11-14 19:25:57 +00003384 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003385 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003386 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003387 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003388 }
3389 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003390
Steve Narofffea763e82007-11-14 19:25:57 +00003391 // Now comment out any visibility specifiers.
3392 while (cursor < endBuf) {
3393 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003394 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003395 // Skip whitespace.
3396 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3397 /*scan*/;
3398
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003399 // FIXME: presence of @public, etc. inside comment results in
3400 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003401 if (!strncmp(cursor, "public", strlen("public")) ||
3402 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003403 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003404 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003405 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003406 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003407 // FIXME: If there are cases where '<' is used in ivar declaration part
3408 // of user code, then scan the ivar list and use needToScanForQualifiers
3409 // for type checking.
3410 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003411 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003412 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003413 cursor = strchr(cursor, '>');
3414 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003415 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003416 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003417 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003418 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003419 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003420 }
Steve Narofffea763e82007-11-14 19:25:57 +00003421 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003422 }
Steve Narofffea763e82007-11-14 19:25:57 +00003423 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003424 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003425 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003426 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003427 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003428 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003429 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003430 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003431 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003432 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003433 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003434 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003435 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003436 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003437}
3438
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003439// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003440/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003441template<typename MethodIterator>
3442void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3443 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003444 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003445 StringRef prefix,
3446 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003447 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003448 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003450 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003451 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003452 SEL _cmd;
3453 char *method_types;
3454 void *_imp;
3455 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003456 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003457 Result += "\nstruct _objc_method {\n";
3458 Result += "\tSEL _cmd;\n";
3459 Result += "\tchar *method_types;\n";
3460 Result += "\tvoid *_imp;\n";
3461 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003463 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003464 }
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003466 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Steve Naroff946a6932008-03-11 00:12:29 +00003468 /* struct {
3469 struct _objc_method_list *next_method;
3470 int method_count;
3471 struct _objc_method method_list[];
3472 }
3473 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003474 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003475 Result += "\nstatic struct {\n";
3476 Result += "\tstruct _objc_method_list *next_method;\n";
3477 Result += "\tint method_count;\n";
3478 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003479 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003480 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003481 Result += prefix;
3482 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3483 Result += "_METHODS_";
3484 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003485 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003486 Result += IsInstanceMethod ? "inst" : "cls";
3487 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003488 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003489
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003490 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003491 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003492 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003493 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003494 Result += "\", \"";
3495 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003496 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003497 Result += MethodInternalNames[*MethodBegin];
3498 Result += "}\n";
3499 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3500 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003501 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003502 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003503 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003504 Result += "\", \"";
3505 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003506 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003507 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003508 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003509 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003510 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003511}
3512
Steve Naroff621edce2009-04-29 16:37:50 +00003513/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003514void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003515RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3516 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003517 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003518
3519 // Output struct protocol_methods holder of method selector and type.
3520 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3521 /* struct protocol_methods {
3522 SEL _cmd;
3523 char *method_types;
3524 }
3525 */
3526 Result += "\nstruct _protocol_methods {\n";
3527 Result += "\tstruct objc_selector *_cmd;\n";
3528 Result += "\tchar *method_types;\n";
3529 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Steve Naroff621edce2009-04-29 16:37:50 +00003531 objc_protocol_methods = true;
3532 }
3533 // Do not synthesize the protocol more than once.
3534 if (ObjCSynthesizedProtocols.count(PDecl))
3535 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003537 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3538 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3539 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003540 /* struct _objc_protocol_method_list {
3541 int protocol_method_count;
3542 struct protocol_methods protocols[];
3543 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003544 */
Steve Naroff621edce2009-04-29 16:37:50 +00003545 Result += "\nstatic struct {\n";
3546 Result += "\tint protocol_method_count;\n";
3547 Result += "\tstruct _protocol_methods protocol_methods[";
3548 Result += utostr(NumMethods);
3549 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3550 Result += PDecl->getNameAsString();
3551 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3552 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Steve Naroff621edce2009-04-29 16:37:50 +00003554 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003555 for (ObjCProtocolDecl::instmeth_iterator
3556 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003557 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003558 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003559 Result += "\t ,{{(struct objc_selector *)\"";
3560 else
3561 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003562 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003563 std::string MethodTypeString;
3564 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3565 Result += "\", \"";
3566 Result += MethodTypeString;
3567 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003568 }
Steve Naroff621edce2009-04-29 16:37:50 +00003569 Result += "\t }\n};\n";
3570 }
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Steve Naroff621edce2009-04-29 16:37:50 +00003572 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003573 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3574 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003575 if (NumMethods > 0) {
3576 /* struct _objc_protocol_method_list {
3577 int protocol_method_count;
3578 struct protocol_methods protocols[];
3579 }
3580 */
3581 Result += "\nstatic struct {\n";
3582 Result += "\tint protocol_method_count;\n";
3583 Result += "\tstruct _protocol_methods protocol_methods[";
3584 Result += utostr(NumMethods);
3585 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3586 Result += PDecl->getNameAsString();
3587 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3588 "{\n\t";
3589 Result += utostr(NumMethods);
3590 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Steve Naroff621edce2009-04-29 16:37:50 +00003592 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003593 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003594 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003595 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003596 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003597 Result += "\t ,{{(struct objc_selector *)\"";
3598 else
3599 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003600 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003601 std::string MethodTypeString;
3602 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3603 Result += "\", \"";
3604 Result += MethodTypeString;
3605 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003606 }
Steve Naroff621edce2009-04-29 16:37:50 +00003607 Result += "\t }\n};\n";
3608 }
3609
3610 // Output:
3611 /* struct _objc_protocol {
3612 // Objective-C 1.0 extensions
3613 struct _objc_protocol_extension *isa;
3614 char *protocol_name;
3615 struct _objc_protocol **protocol_list;
3616 struct _objc_protocol_method_list *instance_methods;
3617 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003618 };
Steve Naroff621edce2009-04-29 16:37:50 +00003619 */
3620 static bool objc_protocol = false;
3621 if (!objc_protocol) {
3622 Result += "\nstruct _objc_protocol {\n";
3623 Result += "\tstruct _objc_protocol_extension *isa;\n";
3624 Result += "\tchar *protocol_name;\n";
3625 Result += "\tstruct _objc_protocol **protocol_list;\n";
3626 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3627 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003628 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003629
Steve Naroff621edce2009-04-29 16:37:50 +00003630 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003631 }
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Steve Naroff621edce2009-04-29 16:37:50 +00003633 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3634 Result += PDecl->getNameAsString();
3635 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3636 "{\n\t0, \"";
3637 Result += PDecl->getNameAsString();
3638 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003639 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003640 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3641 Result += PDecl->getNameAsString();
3642 Result += ", ";
3643 }
3644 else
3645 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003646 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003647 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3648 Result += PDecl->getNameAsString();
3649 Result += "\n";
3650 }
3651 else
3652 Result += "0\n";
3653 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Steve Naroff621edce2009-04-29 16:37:50 +00003655 // Mark this protocol as having been generated.
3656 if (!ObjCSynthesizedProtocols.insert(PDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003657 llvm_unreachable("protocol already synthesized");
Steve Naroff621edce2009-04-29 16:37:50 +00003658
3659}
3660
3661void RewriteObjC::
3662RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003663 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003664 std::string &Result) {
3665 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Steve Naroff621edce2009-04-29 16:37:50 +00003667 for (unsigned i = 0; i != Protocols.size(); i++)
3668 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3669
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003670 // Output the top lovel protocol meta-data for the class.
3671 /* struct _objc_protocol_list {
3672 struct _objc_protocol_list *next;
3673 int protocol_count;
3674 struct _objc_protocol *class_protocols[];
3675 }
3676 */
3677 Result += "\nstatic struct {\n";
3678 Result += "\tstruct _objc_protocol_list *next;\n";
3679 Result += "\tint protocol_count;\n";
3680 Result += "\tstruct _objc_protocol *class_protocols[";
3681 Result += utostr(Protocols.size());
3682 Result += "];\n} _OBJC_";
3683 Result += prefix;
3684 Result += "_PROTOCOLS_";
3685 Result += ClassName;
3686 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3687 "{\n\t0, ";
3688 Result += utostr(Protocols.size());
3689 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003690
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003691 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003692 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003693 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003694
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003695 for (unsigned i = 1; i != Protocols.size(); i++) {
3696 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003697 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003698 Result += "\n";
3699 }
3700 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003701}
3702
Steve Naroff621edce2009-04-29 16:37:50 +00003703
Mike Stump1eb44332009-09-09 15:08:12 +00003704/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003705/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003706void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003707 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003708 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003709 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003710 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003711 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003712 CDecl = CDecl->getNextClassCategory())
3713 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3714 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003716 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003717 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003718 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003720 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003721 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003722 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003723
3724 // If any of our property implementations have associated getters or
3725 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003726 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3727 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003728 Prop != PropEnd; ++Prop) {
3729 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3730 continue;
3731 if (!(*Prop)->getPropertyIvarDecl())
3732 continue;
3733 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3734 if (!PD)
3735 continue;
3736 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3737 InstanceMethods.push_back(Getter);
3738 if (PD->isReadOnly())
3739 continue;
3740 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3741 InstanceMethods.push_back(Setter);
3742 }
3743 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003744 true, "CATEGORY_", FullCategoryName.c_str(),
3745 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003747 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003748 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003749 false, "CATEGORY_", FullCategoryName.c_str(),
3750 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003751
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003752 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003753 // Null CDecl is case of a category implementation with no category interface
3754 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003755 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003756 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003757 /* struct _objc_category {
3758 char *category_name;
3759 char *class_name;
3760 struct _objc_method_list *instance_methods;
3761 struct _objc_method_list *class_methods;
3762 struct _objc_protocol_list *protocols;
3763 // Objective-C 1.0 extensions
3764 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003765 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003766 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003767 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003768 */
Mike Stump1eb44332009-09-09 15:08:12 +00003769
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003770 static bool objc_category = false;
3771 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003772 Result += "\nstruct _objc_category {\n";
3773 Result += "\tchar *category_name;\n";
3774 Result += "\tchar *class_name;\n";
3775 Result += "\tstruct _objc_method_list *instance_methods;\n";
3776 Result += "\tstruct _objc_method_list *class_methods;\n";
3777 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003778 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003779 Result += "\tstruct _objc_property_list *instance_properties;\n";
3780 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003781 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003782 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003783 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3784 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003785 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003786 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003787 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003788 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003789 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003790
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003791 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003792 Result += "\t, (struct _objc_method_list *)"
3793 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3794 Result += FullCategoryName;
3795 Result += "\n";
3796 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003797 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003798 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003799 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003800 Result += "\t, (struct _objc_method_list *)"
3801 "&_OBJC_CATEGORY_CLASS_METHODS_";
3802 Result += FullCategoryName;
3803 Result += "\n";
3804 }
3805 else
3806 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003807
Chris Lattnercafeb352009-02-20 18:18:36 +00003808 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003809 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003810 Result += FullCategoryName;
3811 Result += "\n";
3812 }
3813 else
3814 Result += "\t, 0\n";
3815 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003816}
3817
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003818/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3819/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003820void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003821 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003822 if (ivar->isBitField()) {
3823 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3824 // place all bitfields at offset 0.
3825 Result += "0";
3826 } else {
3827 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003828 Result += ivar->getContainingInterface()->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003829 if (LangOpts.MicrosoftExt)
Steve Naroff8f3b2652008-07-16 18:22:22 +00003830 Result += "_IMPL";
3831 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003832 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003833 Result += ")";
3834 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003835}
3836
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003837//===----------------------------------------------------------------------===//
3838// Meta Data Emission
3839//===----------------------------------------------------------------------===//
3840
Steve Naroffb29b4272008-04-14 22:03:09 +00003841void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003842 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003843 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003845 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003846 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003847 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003848 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003849 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003850 }
Mike Stump1eb44332009-09-09 15:08:12 +00003851
Chris Lattnerbe6df082007-12-12 07:56:42 +00003852 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003853 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003854 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003855 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003856 if (NumIvars > 0) {
3857 static bool objc_ivar = false;
3858 if (!objc_ivar) {
3859 /* struct _objc_ivar {
3860 char *ivar_name;
3861 char *ivar_type;
3862 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003863 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003864 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003865 Result += "\nstruct _objc_ivar {\n";
3866 Result += "\tchar *ivar_name;\n";
3867 Result += "\tchar *ivar_type;\n";
3868 Result += "\tint ivar_offset;\n";
3869 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003870
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003871 objc_ivar = true;
3872 }
3873
Steve Naroff946a6932008-03-11 00:12:29 +00003874 /* struct {
3875 int ivar_count;
3876 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003877 };
Steve Naroff946a6932008-03-11 00:12:29 +00003878 */
Mike Stump1eb44332009-09-09 15:08:12 +00003879 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003880 Result += "\tint ivar_count;\n";
3881 Result += "\tstruct _objc_ivar ivar_list[";
3882 Result += utostr(NumIvars);
3883 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003884 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003885 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003886 "{\n\t";
3887 Result += utostr(NumIvars);
3888 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003889
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003890 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003891 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003892 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003893 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003894 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003895 IV != IVEnd; ++IV)
3896 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003897 IVI = IDecl->ivar_begin();
3898 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003899 } else {
3900 IVI = CDecl->ivar_begin();
3901 IVE = CDecl->ivar_end();
3902 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003903 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003904 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003905 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003906 std::string TmpString, StrEncoding;
3907 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3908 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003909 Result += StrEncoding;
3910 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003911 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003912 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003913 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003914 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003915 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003916 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003917 std::string TmpString, StrEncoding;
3918 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3919 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003920 Result += StrEncoding;
3921 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003922 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003923 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003924 }
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003926 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003927 }
Mike Stump1eb44332009-09-09 15:08:12 +00003928
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003929 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003930 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003931 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003932
3933 // If any of our property implementations have associated getters or
3934 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003935 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3936 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003937 Prop != PropEnd; ++Prop) {
3938 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3939 continue;
3940 if (!(*Prop)->getPropertyIvarDecl())
3941 continue;
3942 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3943 if (!PD)
3944 continue;
3945 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003946 if (!Getter->isDefined())
3947 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003948 if (PD->isReadOnly())
3949 continue;
3950 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003951 if (!Setter->isDefined())
3952 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003953 }
3954 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003955 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003956
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003957 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003958 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003959 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003961 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003962 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003963 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003964
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003965 // Declaration of class/meta-class metadata
3966 /* struct _objc_class {
3967 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003968 const char *super_class_name;
3969 char *name;
3970 long version;
3971 long info;
3972 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003973 struct _objc_ivar_list *ivars;
3974 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003975 struct objc_cache *cache;
3976 struct objc_protocol_list *protocols;
3977 const char *ivar_layout;
3978 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003979 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003980 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003981 static bool objc_class = false;
3982 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003983 Result += "\nstruct _objc_class {\n";
3984 Result += "\tstruct _objc_class *isa;\n";
3985 Result += "\tconst char *super_class_name;\n";
3986 Result += "\tchar *name;\n";
3987 Result += "\tlong version;\n";
3988 Result += "\tlong info;\n";
3989 Result += "\tlong instance_size;\n";
3990 Result += "\tstruct _objc_ivar_list *ivars;\n";
3991 Result += "\tstruct _objc_method_list *methods;\n";
3992 Result += "\tstruct objc_cache *cache;\n";
3993 Result += "\tstruct _objc_protocol_list *protocols;\n";
3994 Result += "\tconst char *ivar_layout;\n";
3995 Result += "\tstruct _objc_class_ext *ext;\n";
3996 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003997 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003998 }
Mike Stump1eb44332009-09-09 15:08:12 +00003999
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004000 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004001 ObjCInterfaceDecl *RootClass = 0;
4002 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004003 while (SuperClass) {
4004 RootClass = SuperClass;
4005 SuperClass = SuperClass->getSuperClass();
4006 }
4007 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004009 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004010 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004011 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004012 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004013 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004014 Result += "\"";
4015
4016 if (SuperClass) {
4017 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004018 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004019 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004020 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004021 Result += "\"";
4022 }
4023 else {
4024 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004025 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004026 Result += "\"";
4027 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004028 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004029 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004030 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004031 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004032 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004033 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004034 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004035 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004036 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004037 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004038 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004039 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004040 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004041 Result += ",0,0\n";
4042 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004043 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004044 Result += "\t,0,0,0,0\n";
4045 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004046
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004047 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004048 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004049 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004050 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004051 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004052 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004053 if (SuperClass) {
4054 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004055 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004056 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004057 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004058 Result += "\"";
4059 }
4060 else {
4061 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004062 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004063 Result += "\"";
4064 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004065 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004066 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004067 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004068 Result += ",0";
4069 else {
4070 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004071 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004072 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00004073 if (LangOpts.MicrosoftExt)
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004074 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004075 Result += ")";
4076 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004077 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004078 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004079 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004080 Result += "\n\t";
4081 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004082 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004083 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004084 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004085 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004086 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004087 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004088 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004089 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004090 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004091 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004092 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004093 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004094 Result += ", 0,0\n";
4095 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004096 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004097 Result += ",0,0,0\n";
4098 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004099}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004100
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004101/// RewriteImplementations - This routine rewrites all method implementations
4102/// and emits meta-data.
4103
Steve Narofface66252008-11-13 20:07:04 +00004104void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004105 int ClsDefCount = ClassImplementation.size();
4106 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004107
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004108 // Rewrite implemented methods
4109 for (int i = 0; i < ClsDefCount; i++)
4110 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004112 for (int i = 0; i < CatDefCount; i++)
4113 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004114}
Mike Stump1eb44332009-09-09 15:08:12 +00004115
Steve Narofface66252008-11-13 20:07:04 +00004116void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4117 int ClsDefCount = ClassImplementation.size();
4118 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004119
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004120 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004121 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004122 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004124 // For each implemented category, write out all its meta data.
4125 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004126 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004127
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004128 // Write objc_symtab metadata
4129 /*
4130 struct _objc_symtab
4131 {
4132 long sel_ref_cnt;
4133 SEL *refs;
4134 short cls_def_cnt;
4135 short cat_def_cnt;
4136 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004137 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004138 */
Mike Stump1eb44332009-09-09 15:08:12 +00004139
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004140 Result += "\nstruct _objc_symtab {\n";
4141 Result += "\tlong sel_ref_cnt;\n";
4142 Result += "\tSEL *refs;\n";
4143 Result += "\tshort cls_def_cnt;\n";
4144 Result += "\tshort cat_def_cnt;\n";
4145 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4146 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004147
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004148 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004149 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004150 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004151 + ", " + utostr(CatDefCount) + "\n";
4152 for (int i = 0; i < ClsDefCount; i++) {
4153 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004154 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004155 Result += "\n";
4156 }
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004158 for (int i = 0; i < CatDefCount; i++) {
4159 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004160 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004161 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004162 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004163 Result += "\n";
4164 }
Mike Stump1eb44332009-09-09 15:08:12 +00004165
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004166 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004168 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004169
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004170 /*
4171 struct _objc_module {
4172 long version;
4173 long size;
4174 const char *name;
4175 struct _objc_symtab *symtab;
4176 }
4177 */
Mike Stump1eb44332009-09-09 15:08:12 +00004178
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004179 Result += "\nstruct _objc_module {\n";
4180 Result += "\tlong version;\n";
4181 Result += "\tlong size;\n";
4182 Result += "\tconst char *name;\n";
4183 Result += "\tstruct _objc_symtab *symtab;\n";
4184 Result += "};\n\n";
4185 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004186 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004187 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004188 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004189 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004190
Francois Pichet62ec1f22011-09-17 17:15:52 +00004191 if (LangOpts.MicrosoftExt) {
Steve Naroff621edce2009-04-29 16:37:50 +00004192 if (ProtocolExprDecls.size()) {
4193 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4194 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004195 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004196 E = ProtocolExprDecls.end(); I != E; ++I) {
4197 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4198 Result += (*I)->getNameAsString();
4199 Result += " = &_OBJC_PROTOCOL_";
4200 Result += (*I)->getNameAsString();
4201 Result += ";\n";
4202 }
4203 Result += "#pragma data_seg(pop)\n\n";
4204 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004205 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004206 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004207 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4208 Result += "&_OBJC_MODULES;\n";
4209 Result += "#pragma data_seg(pop)\n\n";
4210 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004211}
Chris Lattner311ff022007-10-16 22:36:42 +00004212
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004213void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4214 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004215 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004216 assert(BlockByRefDeclNo.count(VD) &&
4217 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004218 if (def)
4219 ResultStr += "struct ";
4220 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004221 "_" + utostr(BlockByRefDeclNo[VD]) ;
4222}
4223
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004224static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4225 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4226 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4227 return false;
4228}
4229
Steve Naroff54055232008-10-27 17:20:55 +00004230std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004231 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004232 std::string Tag) {
4233 const FunctionType *AFT = CE->getFunctionType();
4234 QualType RT = AFT->getResultType();
4235 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00004236 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004237 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004238
Steve Naroff54055232008-10-27 17:20:55 +00004239 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004240
Douglas Gregor72564e72009-02-26 23:50:07 +00004241 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004242 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004243 // block (to reference imported block decl refs).
4244 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004245 } else if (BD->param_empty()) {
4246 S += "(" + StructRef + " *__cself)";
4247 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004248 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004249 assert(FT && "SynthesizeBlockFunc: No function proto");
4250 S += '(';
4251 // first add the implicit argument.
4252 S += StructRef + " *__cself, ";
4253 std::string ParamStr;
4254 for (BlockDecl::param_iterator AI = BD->param_begin(),
4255 E = BD->param_end(); AI != E; ++AI) {
4256 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004257 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004258 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004259 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00004260 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004261 else
Douglas Gregor30c42402011-09-27 22:38:19 +00004262 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004263 S += ParamStr;
4264 }
4265 if (FT->isVariadic()) {
4266 if (!BD->param_empty()) S += ", ";
4267 S += "...";
4268 }
4269 S += ')';
4270 }
4271 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Steve Naroff54055232008-10-27 17:20:55 +00004273 // Create local declarations to avoid rewriting all closure decl ref exprs.
4274 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004275 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004276 E = BlockByRefDecls.end(); I != E; ++I) {
4277 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004278 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004279 std::string TypeString;
4280 RewriteByRefString(TypeString, Name, (*I));
4281 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004282 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004283 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004284 }
Steve Naroff54055232008-10-27 17:20:55 +00004285 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004286 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004287 E = BlockByCopyDecls.end(); I != E; ++I) {
4288 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004289 // Handle nested closure invocation. For example:
4290 //
4291 // void (^myImportedClosure)(void);
4292 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004293 //
Steve Naroff54055232008-10-27 17:20:55 +00004294 // void (^anotherClosure)(void);
4295 // anotherClosure = ^(void) {
4296 // myImportedClosure(); // import and invoke the closure
4297 // };
4298 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004299 if (isTopLevelBlockPointerType((*I)->getType())) {
4300 RewriteBlockPointerTypeVariable(S, (*I));
4301 S += " = (";
4302 RewriteBlockPointerType(S, (*I)->getType());
4303 S += ")";
4304 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4305 }
4306 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004307 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004308 QualType QT = (*I)->getType();
4309 if (HasLocalVariableExternalStorage(*I))
4310 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004311 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004312 S += Name + " = __cself->" +
4313 (*I)->getNameAsString() + "; // bound by copy\n";
4314 }
Steve Naroff54055232008-10-27 17:20:55 +00004315 }
4316 std::string RewrittenStr = RewrittenBlockExprs[CE];
4317 const char *cstr = RewrittenStr.c_str();
4318 while (*cstr++ != '{') ;
4319 S += cstr;
4320 S += "\n";
4321 return S;
4322}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004323
Steve Naroff54055232008-10-27 17:20:55 +00004324std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004325 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004326 std::string Tag) {
4327 std::string StructRef = "struct " + Tag;
4328 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004329
Steve Naroff54055232008-10-27 17:20:55 +00004330 S += funcName;
4331 S += "_block_copy_" + utostr(i);
4332 S += "(" + StructRef;
4333 S += "*dst, " + StructRef;
4334 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004335 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004336 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004337 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004338 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004339 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004340 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004341 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004342 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004343 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004344 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004345 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004346 else
4347 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004348 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004349 S += "}\n";
4350
Steve Naroff54055232008-10-27 17:20:55 +00004351 S += "\nstatic void __";
4352 S += funcName;
4353 S += "_block_dispose_" + utostr(i);
4354 S += "(" + StructRef;
4355 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004356 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004357 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004358 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004359 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004360 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004361 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004362 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004363 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004364 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004365 else
4366 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004367 }
Mike Stump1eb44332009-09-09 15:08:12 +00004368 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004369 return S;
4370}
4371
Steve Naroff01aec112009-12-06 21:14:13 +00004372std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4373 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004374 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004375 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004376
Steve Naroff54055232008-10-27 17:20:55 +00004377 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004378 S += " struct " + Desc;
4379 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004380
Steve Naroff01aec112009-12-06 21:14:13 +00004381 Constructor += "(void *fp, "; // Invoke function pointer.
4382 Constructor += "struct " + Desc; // Descriptor pointer.
4383 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004384
Steve Naroff54055232008-10-27 17:20:55 +00004385 if (BlockDeclRefs.size()) {
4386 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004387 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004388 E = BlockByCopyDecls.end(); I != E; ++I) {
4389 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004390 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004391 std::string ArgName = "_" + FieldName;
4392 // Handle nested closure invocation. For example:
4393 //
4394 // void (^myImportedBlock)(void);
4395 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004396 //
Steve Naroff54055232008-10-27 17:20:55 +00004397 // void (^anotherBlock)(void);
4398 // anotherBlock = ^(void) {
4399 // myImportedBlock(); // import and invoke the closure
4400 // };
4401 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004402 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004403 S += "struct __block_impl *";
4404 Constructor += ", void *" + ArgName;
4405 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004406 QualType QT = (*I)->getType();
4407 if (HasLocalVariableExternalStorage(*I))
4408 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004409 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4410 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004411 Constructor += ", " + ArgName;
4412 }
4413 S += FieldName + ";\n";
4414 }
4415 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004416 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004417 E = BlockByRefDecls.end(); I != E; ++I) {
4418 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004419 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004420 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004421 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004422 std::string TypeString;
4423 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004424 TypeString += " *";
4425 FieldName = TypeString + FieldName;
4426 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004427 Constructor += ", " + ArgName;
4428 }
4429 S += FieldName + "; // by ref\n";
4430 }
4431 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004432 Constructor += ", int flags=0)";
4433 // Initialize all "by copy" arguments.
4434 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004435 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004436 E = BlockByCopyDecls.end(); I != E; ++I) {
4437 std::string Name = (*I)->getNameAsString();
4438 if (firsTime) {
4439 Constructor += " : ";
4440 firsTime = false;
4441 }
4442 else
4443 Constructor += ", ";
4444 if (isTopLevelBlockPointerType((*I)->getType()))
4445 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4446 else
4447 Constructor += Name + "(_" + Name + ")";
4448 }
4449 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004450 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004451 E = BlockByRefDecls.end(); I != E; ++I) {
4452 std::string Name = (*I)->getNameAsString();
4453 if (firsTime) {
4454 Constructor += " : ";
4455 firsTime = false;
4456 }
4457 else
4458 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004459 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004460 }
4461
4462 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004463 if (GlobalVarDecl)
4464 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4465 else
4466 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004467 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004468
Steve Naroff01aec112009-12-06 21:14:13 +00004469 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004470 } else {
4471 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004472 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004473 if (GlobalVarDecl)
4474 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4475 else
4476 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004477 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4478 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004479 }
4480 Constructor += " ";
4481 Constructor += "}\n";
4482 S += Constructor;
4483 S += "};\n";
4484 return S;
4485}
4486
Steve Naroff01aec112009-12-06 21:14:13 +00004487std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4488 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004489 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004490 unsigned hasCopy) {
4491 std::string S = "\nstatic struct " + DescTag;
4492
4493 S += " {\n unsigned long reserved;\n";
4494 S += " unsigned long Block_size;\n";
4495 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004496 S += " void (*copy)(struct ";
4497 S += ImplTag; S += "*, struct ";
4498 S += ImplTag; S += "*);\n";
4499
4500 S += " void (*dispose)(struct ";
4501 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004502 }
4503 S += "} ";
4504
4505 S += DescTag + "_DATA = { 0, sizeof(struct ";
4506 S += ImplTag + ")";
4507 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004508 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4509 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004510 }
4511 S += "};\n";
4512 return S;
4513}
4514
Steve Naroff54055232008-10-27 17:20:55 +00004515void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004516 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004517 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004518 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004519 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004520 bool RewriteSC = (GlobalVarDecl &&
4521 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004522 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004523 GlobalVarDecl->getType().getCVRQualifiers());
4524 if (RewriteSC) {
4525 std::string SC(" void __");
4526 SC += GlobalVarDecl->getNameAsString();
4527 SC += "() {}";
4528 InsertText(FunLocStart, SC);
4529 }
4530
Steve Naroff54055232008-10-27 17:20:55 +00004531 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004532 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4533 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004534 // Need to copy-in the inner copied-in variables not actually used in this
4535 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004536 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4537 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4538 ValueDecl *VD = Exp->getDecl();
4539 BlockDeclRefs.push_back(Exp);
4540 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4541 BlockByCopyDeclsPtrSet.insert(VD);
4542 BlockByCopyDecls.push_back(VD);
4543 }
4544 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4545 BlockByRefDeclsPtrSet.insert(VD);
4546 BlockByRefDecls.push_back(VD);
4547 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004548 // imported objects in the inner blocks not used in the outer
4549 // blocks must be copied/disposed in the outer block as well.
4550 if (Exp->isByRef() ||
4551 VD->getType()->isObjCObjectPointerType() ||
4552 VD->getType()->isBlockPointerType())
4553 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004554 }
Steve Naroff54055232008-10-27 17:20:55 +00004555
Daniel Dunbar4087f272010-08-17 22:39:59 +00004556 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4557 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004558
Steve Naroff01aec112009-12-06 21:14:13 +00004559 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004560
Benjamin Kramerd999b372010-02-14 14:14:16 +00004561 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004562
Steve Naroff01aec112009-12-06 21:14:13 +00004563 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004564
Benjamin Kramerd999b372010-02-14 14:14:16 +00004565 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004566
4567 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004568 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004569 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004570 }
Steve Naroff01aec112009-12-06 21:14:13 +00004571 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4572 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004573 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004574
Steve Naroff54055232008-10-27 17:20:55 +00004575 BlockDeclRefs.clear();
4576 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004577 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004578 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004579 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004580 ImportedBlockDecls.clear();
4581 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004582 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004583 // Must insert any 'const/volatile/static here. Since it has been
4584 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004585 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004586 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004587 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004588 if (GlobalVarDecl->getType().isConstQualified())
4589 SC += "const ";
4590 if (GlobalVarDecl->getType().isVolatileQualified())
4591 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004592 if (GlobalVarDecl->getType().isRestrictQualified())
4593 SC += "restrict ";
4594 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004595 }
4596
Steve Naroff54055232008-10-27 17:20:55 +00004597 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004598 InnerDeclRefsCount.clear();
4599 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004600 RewrittenBlockExprs.clear();
4601}
4602
4603void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4604 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004605 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004606
Steve Naroff54055232008-10-27 17:20:55 +00004607 SynthesizeBlockLiterals(FunLocStart, FuncName);
4608}
4609
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004610static void BuildUniqueMethodName(std::string &Name,
4611 ObjCMethodDecl *MD) {
4612 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004613 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004614 Name += "__" + MD->getSelector().getAsString();
4615 // Convert colons to underscores.
4616 std::string::size_type loc = 0;
4617 while ((loc = Name.find(":", loc)) != std::string::npos)
4618 Name.replace(loc, 1, "_");
4619}
4620
Steve Naroff54055232008-10-27 17:20:55 +00004621void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004622 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4623 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004624 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004625 std::string FuncName;
4626 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004627 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004628}
4629
4630void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004631 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004632 if (*CI) {
4633 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4634 GetBlockDeclRefExprs(CBE->getBody());
4635 else
4636 GetBlockDeclRefExprs(*CI);
4637 }
4638 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004639 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004640 // FIXME: Handle enums.
4641 if (!isa<FunctionDecl>(CDRE->getDecl()))
4642 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004643 }
4644 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4645 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4646 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004647 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4648 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004649 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004650 BlockDeclRefs.push_back(BDRE);
4651 }
4652
Steve Naroff54055232008-10-27 17:20:55 +00004653 return;
4654}
4655
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004656void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004657 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004658 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004659 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004660 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004661 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4662 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004663 GetInnerBlockDeclRefExprs(CBE->getBody(),
4664 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004665 InnerContexts);
4666 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004667 else
4668 GetInnerBlockDeclRefExprs(*CI,
4669 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004670 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004671
4672 }
4673 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004674 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004675 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004676 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004677 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004678 }
4679 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4680 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4681 if (Var->isFunctionOrMethodVarDecl())
4682 ImportedLocalExternalDecls.insert(Var);
4683 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004684
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004685 return;
4686}
4687
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004688/// convertFunctionTypeOfBlocks - This routine converts a function type
4689/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004690/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004691/// all block pointers to function pointers.
4692QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4693 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4694 // FTP will be null for closures that don't take arguments.
4695 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004696 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004697 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004698 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004699
4700 if (FTP) {
4701 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4702 E = FTP->arg_type_end(); I && (I != E); ++I) {
4703 QualType t = *I;
4704 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004705 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004706 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004707 ArgTypes.push_back(t);
4708 }
4709 }
4710 QualType FuncType;
4711 // FIXME. Does this work if block takes no argument but has a return type
4712 // which is of block type?
4713 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004714 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004715 else FuncType = QualType(FT, 0);
4716 return FuncType;
4717}
4718
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004719Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004720 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004721 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004723 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004724 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004725 } else if (const BlockDeclRefExpr *CDRE =
4726 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004727 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004728 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004729 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004730 }
4731 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4732 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4733 }
4734 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4735 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4736 else if (const ConditionalOperator *CEXPR =
4737 dyn_cast<ConditionalOperator>(BlockExp)) {
4738 Expr *LHSExp = CEXPR->getLHS();
4739 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4740 Expr *RHSExp = CEXPR->getRHS();
4741 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4742 Expr *CONDExp = CEXPR->getCond();
4743 ConditionalOperator *CondExpr =
4744 new (Context) ConditionalOperator(CONDExp,
4745 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004746 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004747 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004748 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004749 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4750 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004751 } else {
4752 assert(1 && "RewriteBlockClass: Bad type");
4753 }
4754 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004755 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004756 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004757 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004758 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004760 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004761 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004762 &Context->Idents.get("__block_impl"));
4763 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004764
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004765 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004766 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004767
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004768 // Push the block argument type.
4769 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004770 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004771 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004772 E = FTP->arg_type_end(); I && (I != E); ++I) {
4773 QualType t = *I;
4774 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004775 if (!convertBlockPointerToFunctionPointer(t))
4776 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004777 ArgTypes.push_back(t);
4778 }
Steve Naroff54055232008-10-27 17:20:55 +00004779 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004780 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004781 QualType PtrToFuncCastType
4782 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004783
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004784 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004785
John McCall9d125032010-01-15 18:39:57 +00004786 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004787 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004788 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004789 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004790 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4791 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004792 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004793
Douglas Gregor44b43212008-12-11 16:49:14 +00004794 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004795 SourceLocation(),
4796 &Context->Idents.get("FuncPtr"),
4797 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004798 /*BitWidth=*/0, /*Mutable=*/true,
4799 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004800 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004801 FD->getType(), VK_LValue,
4802 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004803
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004804
John McCall9d125032010-01-15 18:39:57 +00004805 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004806 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004807 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004808
Chris Lattner5f9e2722011-07-23 10:55:15 +00004809 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004810 // Add the implicit argument.
4811 BlkExprs.push_back(BlkCast);
4812 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004813 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004814 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004815 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004816 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004817 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4818 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004819 Exp->getType(), VK_RValue,
4820 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004821 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004822}
4823
Steve Naroff621edce2009-04-29 16:37:50 +00004824// We need to return the rewritten expression to handle cases where the
4825// BlockDeclRefExpr is embedded in another expression being rewritten.
4826// For example:
4827//
4828// int main() {
4829// __block Foo *f;
4830// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004831//
Steve Naroff621edce2009-04-29 16:37:50 +00004832// void (^myblock)() = ^() {
4833// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4834// i = 77;
4835// };
4836//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004837Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004838 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004839 // for each DeclRefExp where BYREFVAR is name of the variable.
4840 ValueDecl *VD;
4841 bool isArrow = true;
4842 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4843 VD = BDRE->getDecl();
4844 else {
4845 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4846 isArrow = false;
4847 }
4848
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004849 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004850 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004851 &Context->Idents.get("__forwarding"),
4852 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004853 /*BitWidth=*/0, /*Mutable=*/true,
4854 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004855 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4856 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004857 FD->getType(), VK_LValue,
4858 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004859
Chris Lattner5f9e2722011-07-23 10:55:15 +00004860 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004861 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004862 &Context->Idents.get(Name),
4863 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004864 /*BitWidth=*/0, /*Mutable=*/true,
4865 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004866 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004867 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004868
4869
4870
Steve Naroffdf8570d2009-02-02 17:19:26 +00004871 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004872 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4873 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004874 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004875 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004876 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004877}
4878
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004879// Rewrites the imported local variable V with external storage
4880// (static, extern, etc.) as *V
4881//
4882Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4883 ValueDecl *VD = DRE->getDecl();
4884 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4885 if (!ImportedLocalExternalDecls.count(Var))
4886 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004887 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4888 VK_LValue, OK_Ordinary,
4889 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004890 // Need parens to enforce precedence.
4891 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4892 Exp);
4893 ReplaceStmt(DRE, PE);
4894 return PE;
4895}
4896
Steve Naroffb2f9e512008-11-03 23:29:32 +00004897void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4898 SourceLocation LocStart = CE->getLParenLoc();
4899 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004900
4901 // Need to avoid trying to rewrite synthesized casts.
4902 if (LocStart.isInvalid())
4903 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004904 // Need to avoid trying to rewrite casts contained in macros.
4905 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4906 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004907
Steve Naroff54055232008-10-27 17:20:55 +00004908 const char *startBuf = SM->getCharacterData(LocStart);
4909 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004910 QualType QT = CE->getType();
4911 const Type* TypePtr = QT->getAs<Type>();
4912 if (isa<TypeOfExprType>(TypePtr)) {
4913 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4914 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4915 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004916 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004917 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004918 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004919 return;
4920 }
Steve Naroff54055232008-10-27 17:20:55 +00004921 // advance the location to startArgList.
4922 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004923
Steve Naroff54055232008-10-27 17:20:55 +00004924 while (*argPtr++ && (argPtr < endBuf)) {
4925 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004926 case '^':
4927 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004928 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004929 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004930 break;
Steve Naroff54055232008-10-27 17:20:55 +00004931 }
4932 }
4933 return;
4934}
4935
4936void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4937 SourceLocation DeclLoc = FD->getLocation();
4938 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004939
Steve Naroff54055232008-10-27 17:20:55 +00004940 // We have 1 or more arguments that have closure pointers.
4941 const char *startBuf = SM->getCharacterData(DeclLoc);
4942 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004943
Steve Naroff54055232008-10-27 17:20:55 +00004944 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004945
Steve Naroff54055232008-10-27 17:20:55 +00004946 parenCount++;
4947 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004948 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004949 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004950
Steve Naroff54055232008-10-27 17:20:55 +00004951 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004952
Steve Naroff54055232008-10-27 17:20:55 +00004953 while (*argPtr++ && parenCount) {
4954 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004955 case '^':
4956 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004957 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004958 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004959 break;
4960 case '(':
4961 parenCount++;
4962 break;
4963 case ')':
4964 parenCount--;
4965 break;
Steve Naroff54055232008-10-27 17:20:55 +00004966 }
4967 }
4968 return;
4969}
4970
4971bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004972 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004973 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004974 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004975 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004976 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004977 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004978 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004979 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004980 }
4981 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004982 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004983 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004984 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004985 return true;
4986 }
4987 return false;
4988}
4989
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004990bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4991 const FunctionProtoType *FTP;
4992 const PointerType *PT = QT->getAs<PointerType>();
4993 if (PT) {
4994 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4995 } else {
4996 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4997 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4998 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4999 }
5000 if (FTP) {
5001 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00005002 E = FTP->arg_type_end(); I != E; ++I) {
5003 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005004 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00005005 if ((*I)->isObjCObjectPointerType() &&
5006 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5007 return true;
5008 }
5009
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005010 }
5011 return false;
5012}
5013
Ted Kremenek8189cde2009-02-07 01:47:29 +00005014void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5015 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00005016 const char *argPtr = strchr(Name, '(');
5017 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00005018
Steve Naroff54055232008-10-27 17:20:55 +00005019 LParen = argPtr; // output the start.
5020 argPtr++; // skip past the left paren.
5021 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005022
Steve Naroff54055232008-10-27 17:20:55 +00005023 while (*argPtr && parenCount) {
5024 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00005025 case '(': parenCount++; break;
5026 case ')': parenCount--; break;
5027 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005028 }
5029 if (parenCount) argPtr++;
5030 }
5031 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5032 RParen = argPtr; // output the end
5033}
5034
5035void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5036 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5037 RewriteBlockPointerFunctionArgs(FD);
5038 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005039 }
Steve Naroff54055232008-10-27 17:20:55 +00005040 // Handle Variables and Typedefs.
5041 SourceLocation DeclLoc = ND->getLocation();
5042 QualType DeclT;
5043 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5044 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005045 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005046 DeclT = TDD->getUnderlyingType();
5047 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5048 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005049 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005050 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005051
Steve Naroff54055232008-10-27 17:20:55 +00005052 const char *startBuf = SM->getCharacterData(DeclLoc);
5053 const char *endBuf = startBuf;
5054 // scan backward (from the decl location) for the end of the previous decl.
5055 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5056 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005057 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005058 std::string buf;
5059 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005060 // *startBuf != '^' if we are dealing with a pointer to function that
5061 // may take block argument types (which will be handled below).
5062 if (*startBuf == '^') {
5063 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005064 buf = '*';
5065 startBuf++;
5066 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005067 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005068 while (*startBuf != ')') {
5069 buf += *startBuf;
5070 startBuf++;
5071 OrigLength++;
5072 }
5073 buf += ')';
5074 OrigLength++;
5075
5076 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5077 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005078 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005079 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005080 DeclLoc = ND->getLocation();
5081 startBuf = SM->getCharacterData(DeclLoc);
5082 const char *argListBegin, *argListEnd;
5083 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5084 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005085 if (*argListBegin == '^')
5086 buf += '*';
5087 else if (*argListBegin == '<') {
5088 buf += "/*";
5089 buf += *argListBegin++;
5090 OrigLength++;;
5091 while (*argListBegin != '>') {
5092 buf += *argListBegin++;
5093 OrigLength++;
5094 }
5095 buf += *argListBegin;
5096 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005097 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005098 else
5099 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005100 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005101 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005102 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005103 buf += ')';
5104 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005105 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005106 ReplaceText(Start, OrigLength, buf);
5107
Steve Naroff54055232008-10-27 17:20:55 +00005108 return;
5109}
5110
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005111
5112/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5113/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5114/// struct Block_byref_id_object *src) {
5115/// _Block_object_assign (&_dest->object, _src->object,
5116/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5117/// [|BLOCK_FIELD_IS_WEAK]) // object
5118/// _Block_object_assign(&_dest->object, _src->object,
5119/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5120/// [|BLOCK_FIELD_IS_WEAK]) // block
5121/// }
5122/// And:
5123/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5124/// _Block_object_dispose(_src->object,
5125/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5126/// [|BLOCK_FIELD_IS_WEAK]) // object
5127/// _Block_object_dispose(_src->object,
5128/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5129/// [|BLOCK_FIELD_IS_WEAK]) // block
5130/// }
5131
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005132std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5133 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005134 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005135 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005136 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005137 CopyDestroyCache.insert(flag);
5138 S = "static void __Block_byref_id_object_copy_";
5139 S += utostr(flag);
5140 S += "(void *dst, void *src) {\n";
5141
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005142 // offset into the object pointer is computed as:
5143 // void * + void* + int + int + void* + void *
5144 unsigned IntSize =
5145 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5146 unsigned VoidPtrSize =
5147 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5148
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005149 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005150 S += " _Block_object_assign((char*)dst + ";
5151 S += utostr(offset);
5152 S += ", *(void * *) ((char*)src + ";
5153 S += utostr(offset);
5154 S += "), ";
5155 S += utostr(flag);
5156 S += ");\n}\n";
5157
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005158 S += "static void __Block_byref_id_object_dispose_";
5159 S += utostr(flag);
5160 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005161 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5162 S += utostr(offset);
5163 S += "), ";
5164 S += utostr(flag);
5165 S += ");\n}\n";
5166 return S;
5167}
5168
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005169/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5170/// the declaration into:
5171/// struct __Block_byref_ND {
5172/// void *__isa; // NULL for everything except __weak pointers
5173/// struct __Block_byref_ND *__forwarding;
5174/// int32_t __flags;
5175/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005176/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5177/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005178/// typex ND;
5179/// };
5180///
5181/// It then replaces declaration of ND variable with:
5182/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5183/// __size=sizeof(struct __Block_byref_ND),
5184/// ND=initializer-if-any};
5185///
5186///
5187void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005188 // Insert declaration for the function in which block literal is
5189 // used.
5190 if (CurFunctionDeclToDeclareForBlock)
5191 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005192 int flag = 0;
5193 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005194 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005195 if (DeclLoc.isInvalid())
5196 // If type location is missing, it is because of missing type (a warning).
5197 // Use variable's location which is good for this case.
5198 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005199 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005200 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005201 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005202 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005203 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005204 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005205 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005206 ByrefType += " {\n";
5207 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005208 RewriteByRefString(ByrefType, Name, ND);
5209 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005210 ByrefType += " int __flags;\n";
5211 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005212 // Add void *__Block_byref_id_object_copy;
5213 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005214 QualType Ty = ND->getType();
5215 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5216 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005217 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5218 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005219 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005220
5221 QualType T = Ty;
5222 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00005223 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005224
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005225 ByrefType += " " + Name + ";\n";
5226 ByrefType += "};\n";
5227 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005228 SourceLocation FunLocStart;
5229 if (CurFunctionDef)
5230 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5231 else {
5232 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5233 FunLocStart = CurMethodDef->getLocStart();
5234 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005235 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005236 if (Ty.isObjCGCWeak()) {
5237 flag |= BLOCK_FIELD_IS_WEAK;
5238 isa = 1;
5239 }
5240
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005241 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005242 flag = BLOCK_BYREF_CALLER;
5243 QualType Ty = ND->getType();
5244 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5245 if (Ty->isBlockPointerType())
5246 flag |= BLOCK_FIELD_IS_BLOCK;
5247 else
5248 flag |= BLOCK_FIELD_IS_OBJECT;
5249 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005250 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005251 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005252 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005253
5254 // struct __Block_byref_ND ND =
5255 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5256 // initializer-if-any};
5257 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005258 unsigned flags = 0;
5259 if (HasCopyAndDispose)
5260 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005261 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005262 ByrefType.clear();
5263 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005264 std::string ForwardingCastType("(");
5265 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005266 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005267 ByrefType += " " + Name + " = {(void*)";
5268 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005269 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005270 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005271 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005272 ByrefType += "sizeof(";
5273 RewriteByRefString(ByrefType, Name, ND);
5274 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005275 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005276 ByrefType += ", __Block_byref_id_object_copy_";
5277 ByrefType += utostr(flag);
5278 ByrefType += ", __Block_byref_id_object_dispose_";
5279 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005280 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005281 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005282 unsigned nameSize = Name.size();
5283 // for block or function pointer declaration. Name is aleady
5284 // part of the declaration.
5285 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5286 nameSize = 1;
5287 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005288 }
5289 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005290 SourceLocation startLoc;
5291 Expr *E = ND->getInit();
5292 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5293 startLoc = ECE->getLParenLoc();
5294 else
5295 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005296 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005297 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005298 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005299 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005300 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005301 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005302 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005303 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005304 ByrefType += "sizeof(";
5305 RewriteByRefString(ByrefType, Name, ND);
5306 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005307 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005308 ByrefType += "__Block_byref_id_object_copy_";
5309 ByrefType += utostr(flag);
5310 ByrefType += ", __Block_byref_id_object_dispose_";
5311 ByrefType += utostr(flag);
5312 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005313 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005314 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005315
5316 // Complete the newly synthesized compound expression by inserting a right
5317 // curly brace before the end of the declaration.
5318 // FIXME: This approach avoids rewriting the initializer expression. It
5319 // also assumes there is only one declarator. For example, the following
5320 // isn't currently supported by this routine (in general):
5321 //
5322 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5323 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005324 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5325 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005326 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5327 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005328 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005329
Benjamin Kramerd999b372010-02-14 14:14:16 +00005330 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005331 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005332 return;
5333}
5334
Mike Stump1eb44332009-09-09 15:08:12 +00005335void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005336 // Add initializers for any closure decl refs.
5337 GetBlockDeclRefExprs(Exp->getBody());
5338 if (BlockDeclRefs.size()) {
5339 // Unique all "by copy" declarations.
5340 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005341 if (!BlockDeclRefs[i]->isByRef()) {
5342 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5343 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5344 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5345 }
5346 }
Steve Naroff54055232008-10-27 17:20:55 +00005347 // Unique all "by ref" declarations.
5348 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5349 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005350 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5351 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5352 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5353 }
Steve Naroff54055232008-10-27 17:20:55 +00005354 }
5355 // Find any imported blocks...they will need special attention.
5356 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005357 if (BlockDeclRefs[i]->isByRef() ||
5358 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005359 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005360 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005361 }
5362}
5363
Chris Lattner5f9e2722011-07-23 10:55:15 +00005364FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005365 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005366 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005367 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5368 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005369 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005370}
5371
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005372Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005373 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005374 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005375 Blocks.push_back(Exp);
5376
5377 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005378
5379 // Add inner imported variables now used in current block.
5380 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005381 if (!InnerBlockDeclRefs.empty()) {
5382 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5383 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5384 ValueDecl *VD = Exp->getDecl();
5385 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005386 // We need to save the copied-in variables in nested
5387 // blocks because it is needed at the end for some of the API generations.
5388 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005389 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5390 BlockDeclRefs.push_back(Exp);
5391 BlockByCopyDeclsPtrSet.insert(VD);
5392 BlockByCopyDecls.push_back(VD);
5393 }
5394 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5395 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5396 BlockDeclRefs.push_back(Exp);
5397 BlockByRefDeclsPtrSet.insert(VD);
5398 BlockByRefDecls.push_back(VD);
5399 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005400 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005401 // Find any imported blocks...they will need special attention.
5402 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5403 if (InnerBlockDeclRefs[i]->isByRef() ||
5404 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5405 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5406 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005407 }
5408 InnerDeclRefsCount.push_back(countOfInnerDecls);
5409
Steve Narofffa15fd92008-10-28 20:29:00 +00005410 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005411
Steve Narofffa15fd92008-10-28 20:29:00 +00005412 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005413 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005414 else if (CurMethodDef)
5415 BuildUniqueMethodName(FuncName, CurMethodDef);
5416 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005417 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005418
Steve Narofffa15fd92008-10-28 20:29:00 +00005419 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005420
Steve Narofffa15fd92008-10-28 20:29:00 +00005421 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5422 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005423
Steve Narofffa15fd92008-10-28 20:29:00 +00005424 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005425 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5426 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005427
5428 FunctionDecl *FD;
5429 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005430
Steve Narofffa15fd92008-10-28 20:29:00 +00005431 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005432 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005433 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5434 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005435
Chris Lattner5f9e2722011-07-23 10:55:15 +00005436 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005437
Steve Narofffdc03722008-10-29 21:23:59 +00005438 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005439 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005440 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005441 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005442 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005443 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005444 InitExprs.push_back(castExpr);
5445
Steve Naroff01aec112009-12-06 21:14:13 +00005446 // Initialize the block descriptor.
5447 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005448
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005449 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5450 SourceLocation(), SourceLocation(),
5451 &Context->Idents.get(DescData.c_str()),
5452 Context->VoidPtrTy, 0,
5453 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005454 UnaryOperator *DescRefExpr =
5455 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5456 Context->VoidPtrTy,
5457 VK_LValue,
5458 SourceLocation()),
5459 UO_AddrOf,
5460 Context->getPointerType(Context->VoidPtrTy),
5461 VK_RValue, OK_Ordinary,
5462 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005463 InitExprs.push_back(DescRefExpr);
5464
Steve Narofffa15fd92008-10-28 20:29:00 +00005465 // Add initializers for any closure decl refs.
5466 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005467 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005468 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005469 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005470 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005471 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005472 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005473 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005474 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5475 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005476 if (HasLocalVariableExternalStorage(*I)) {
5477 QualType QT = (*I)->getType();
5478 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005479 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5480 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005481 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005482 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005483 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005484 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5485 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005486 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005487 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005488 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005489 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005490 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5491 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005492 if (HasLocalVariableExternalStorage(*I)) {
5493 QualType QT = (*I)->getType();
5494 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005495 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5496 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005497 }
5498
Steve Narofffa15fd92008-10-28 20:29:00 +00005499 }
Mike Stump1eb44332009-09-09 15:08:12 +00005500 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005501 }
5502 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005503 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005504 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005505 ValueDecl *ND = (*I);
5506 std::string Name(ND->getNameAsString());
5507 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005508 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005509 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5510 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005511 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005512 SourceLocation(), SourceLocation(),
5513 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005514 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5515 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5516
Daniel Dunbar4087f272010-08-17 22:39:59 +00005517 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005518 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5519 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005520 bool isNestedCapturedVar = false;
5521 if (block)
5522 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5523 ce = block->capture_end(); ci != ce; ++ci) {
5524 const VarDecl *variable = ci->getVariable();
5525 if (variable == ND && ci->isNested()) {
5526 assert (ci->isByRef() &&
5527 "SynthBlockInitExpr - captured block variable is not byref");
5528 isNestedCapturedVar = true;
5529 break;
5530 }
5531 }
5532 // captured nested byref variable has its address passed. Do not take
5533 // its address again.
5534 if (!isNestedCapturedVar)
5535 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005536 Context->getPointerType(Exp->getType()),
5537 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005538 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005539 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005540 }
5541 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005542 if (ImportedBlockDecls.size()) {
5543 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5544 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005545 unsigned IntSize =
5546 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005547 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5548 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005549 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005550 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005551 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005552 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005553 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005554 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005555 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005556 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005557 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005558 BlockDeclRefs.clear();
5559 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005560 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005561 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005562 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005563 ImportedBlockDecls.clear();
5564 return NewRep;
5565}
5566
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005567bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5568 if (const ObjCForCollectionStmt * CS =
5569 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5570 return CS->getElement() == DS;
5571 return false;
5572}
5573
Steve Narofffa15fd92008-10-28 20:29:00 +00005574//===----------------------------------------------------------------------===//
5575// Function Body / Expression rewriting
5576//===----------------------------------------------------------------------===//
5577
Steve Naroffc77a6362008-12-04 16:24:46 +00005578// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5579// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5580// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5581// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5582// Since the rewriter isn't capable of rewriting rewritten code, it's important
5583// we get this right.
5584void RewriteObjC::CollectPropertySetters(Stmt *S) {
5585 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005586 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005587 if (*CI)
5588 CollectPropertySetters(*CI);
5589
5590 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5591 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005592 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5593 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005594 }
5595 }
5596}
5597
Steve Narofffa15fd92008-10-28 20:29:00 +00005598Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005599 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005600 isa<DoStmt>(S) || isa<ForStmt>(S))
5601 Stmts.push_back(S);
5602 else if (isa<ObjCForCollectionStmt>(S)) {
5603 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005604 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005605 }
Mike Stump1eb44332009-09-09 15:08:12 +00005606
Steve Narofffa15fd92008-10-28 20:29:00 +00005607 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005608
Steve Narofffa15fd92008-10-28 20:29:00 +00005609 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005610 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005611 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005612 Stmt *newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005613 Stmt *ChildStmt = (*CI);
5614 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005615 Expr *OldBase = IvarRefExpr->getBase();
5616 bool replaced = false;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005617 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005618 if (replaced) {
5619 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5620 ReplaceStmt(OldBase, IRE->getBase());
5621 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005622 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005623 }
5624 }
5625 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005626 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5627 if (newStmt) {
5628 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5629 if (PropSetters[PropOrImplicitRefExpr] == S) {
5630 S = newStmt;
5631 newStmt = 0;
5632 }
5633 if (newStmt)
5634 *CI = newStmt;
5635 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005636 // If dealing with an assignment with LHS being a property reference
5637 // expression, the entire assignment tree is rewritten into a property
5638 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5639 // RHS again.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005640 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCall12f78a62010-12-02 01:19:52 +00005641 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005642 if (PropSetters[Exp]) {
5643 ++CI;
5644 continue;
5645 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005646 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005647 }
Mike Stump1eb44332009-09-09 15:08:12 +00005648
Steve Narofffa15fd92008-10-28 20:29:00 +00005649 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005650 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005651 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5652 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005653 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005654 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005655 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005656 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005657 Stmt *SaveCurrentBody = CurrentBody;
5658 CurrentBody = BE->getBody();
Fariborz Jahanian36178092011-04-08 23:48:29 +00005659 CollectPropertySetters(CurrentBody);
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005660 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005661 // block literal on rhs of a property-dot-sytax assignment
5662 // must be replaced by its synthesize ast so getRewrittenText
5663 // works as expected. In this case, what actually ends up on RHS
5664 // is the blockTranscribed which is the helper function for the
5665 // block literal; as in: self.c = ^() {[ace ARR];};
5666 bool saveDisableReplaceStmt = DisableReplaceStmt;
5667 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005668 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005669 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005670 CurrentBody = SaveCurrentBody;
5671 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005672 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005673 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005674 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005675 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005676
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005677 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5678
Steve Narofffa15fd92008-10-28 20:29:00 +00005679 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005680 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005681 return blockTranscribed;
5682 }
5683 // Handle specific things.
5684 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5685 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005686
John McCall12f78a62010-12-02 01:19:52 +00005687 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005688 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5689 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5690
5691 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005692 if (BinOp) {
5693 // Because the rewriter doesn't allow us to rewrite rewritten code,
5694 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005695 DisableReplaceStmt = true;
5696 // Save the source range. Even if we disable the replacement, the
5697 // rewritten node will have been inserted into the tree. If the synthesized
5698 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005699 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005700 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5701 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005702 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005703 // Need to rewrite the ivar access expression if need be.
5704 if (isa<ObjCIvarRefExpr>(newStmt)) {
5705 bool replaced = false;
5706 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5707 }
5708
Steve Naroffb619d952008-12-09 12:56:34 +00005709 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005710 //
5711 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5712 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5713 // to see the original expression). Consider this example:
5714 //
5715 // Foo *obj1, *obj2;
5716 //
5717 // obj1.i = [obj2 rrrr];
5718 //
5719 // 'BinOp' for the previous expression looks like:
5720 //
5721 // (BinaryOperator 0x231ccf0 'int' '='
5722 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5723 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5724 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5725 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5726 //
5727 // 'newStmt' represents the rewritten message expression. For example:
5728 //
5729 // (CallExpr 0x231d300 'id':'struct objc_object *'
5730 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5731 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5732 // (CStyleCastExpr 0x231d220 'void *'
5733 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5734 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005735 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005736 // can be used as the setter argument. ReplaceStmt() will still 'see'
5737 // the original RHS (since we haven't altered BinOp).
5738 //
Mike Stump1eb44332009-09-09 15:08:12 +00005739 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005740 // node. As a result, we now leak the original AST nodes.
5741 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005742 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005743 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005744 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005745 }
5746 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005747
Steve Narofffa15fd92008-10-28 20:29:00 +00005748 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5749 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005750
Steve Narofffa15fd92008-10-28 20:29:00 +00005751 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5752 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005753
Steve Narofffa15fd92008-10-28 20:29:00 +00005754 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005755#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005756 // Before we rewrite it, put the original message expression in a comment.
5757 SourceLocation startLoc = MessExpr->getLocStart();
5758 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005759
Steve Narofffa15fd92008-10-28 20:29:00 +00005760 const char *startBuf = SM->getCharacterData(startLoc);
5761 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005762
Steve Narofffa15fd92008-10-28 20:29:00 +00005763 std::string messString;
5764 messString += "// ";
5765 messString.append(startBuf, endBuf-startBuf+1);
5766 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005767
5768 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005769 // InsertText(clang::SourceLocation, char const*, unsigned int).
5770 // InsertText(startLoc, messString.c_str(), messString.size());
5771 // Tried this, but it didn't work either...
5772 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005773#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005774 return RewriteMessageExpr(MessExpr);
5775 }
Mike Stump1eb44332009-09-09 15:08:12 +00005776
Steve Narofffa15fd92008-10-28 20:29:00 +00005777 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5778 return RewriteObjCTryStmt(StmtTry);
5779
5780 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5781 return RewriteObjCSynchronizedStmt(StmtTry);
5782
5783 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5784 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005785
Steve Narofffa15fd92008-10-28 20:29:00 +00005786 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5787 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005788
5789 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005790 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005791 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005792 OrigStmtRange.getEnd());
5793 if (BreakStmt *StmtBreakStmt =
5794 dyn_cast<BreakStmt>(S))
5795 return RewriteBreakStmt(StmtBreakStmt);
5796 if (ContinueStmt *StmtContinueStmt =
5797 dyn_cast<ContinueStmt>(S))
5798 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005799
5800 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005801 // and cast exprs.
5802 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5803 // FIXME: What we're doing here is modifying the type-specifier that
5804 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005805 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005806 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5807 // the context of an ObjCForCollectionStmt. For example:
5808 // NSArray *someArray;
5809 // for (id <FooProtocol> index in someArray) ;
5810 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5811 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005812 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005813 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005814
Steve Narofffa15fd92008-10-28 20:29:00 +00005815 // Blocks rewrite rules.
5816 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5817 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005818 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005819 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005820 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005821 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005822 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005823 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005824 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005825 if (VD->hasAttr<BlocksAttr>()) {
5826 static unsigned uniqueByrefDeclCount = 0;
5827 assert(!BlockByRefDeclNo.count(ND) &&
5828 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5829 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005830 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005831 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005832 else
5833 RewriteTypeOfDecl(VD);
5834 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005835 }
Richard Smith162e1c12011-04-15 14:24:37 +00005836 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005837 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005838 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005839 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005840 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5841 }
5842 }
5843 }
Mike Stump1eb44332009-09-09 15:08:12 +00005844
Steve Narofffa15fd92008-10-28 20:29:00 +00005845 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5846 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005847
5848 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005849 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5850 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005851 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5852 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005853 && "Statement stack mismatch");
5854 Stmts.pop_back();
5855 }
5856 // Handle blocks rewriting.
5857 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5858 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005859 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005860 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005861 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5862 ValueDecl *VD = DRE->getDecl();
5863 if (VD->hasAttr<BlocksAttr>())
5864 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005865 if (HasLocalVariableExternalStorage(VD))
5866 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005867 }
5868
Steve Narofffa15fd92008-10-28 20:29:00 +00005869 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005870 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005871 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005872 ReplaceStmt(S, BlockCall);
5873 return BlockCall;
5874 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005875 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005876 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005877 RewriteCastExpr(CE);
5878 }
5879#if 0
5880 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005881 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5882 ICE->getSubExpr(),
5883 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005884 // Get the new text.
5885 std::string SStr;
5886 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005887 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005888 const std::string &Str = Buf.str();
5889
5890 printf("CAST = %s\n", &Str[0]);
5891 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5892 delete S;
5893 return Replacement;
5894 }
5895#endif
5896 // Return this stmt unmodified.
5897 return S;
5898}
5899
Steve Naroff3d7e7862009-12-05 15:55:59 +00005900void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5901 for (RecordDecl::field_iterator i = RD->field_begin(),
5902 e = RD->field_end(); i != e; ++i) {
5903 FieldDecl *FD = *i;
5904 if (isTopLevelBlockPointerType(FD->getType()))
5905 RewriteBlockPointerDecl(FD);
5906 if (FD->getType()->isObjCQualifiedIdType() ||
5907 FD->getType()->isObjCQualifiedInterfaceType())
5908 RewriteObjCQualifiedInterfaceTypes(FD);
5909 }
5910}
5911
Steve Narofffa15fd92008-10-28 20:29:00 +00005912/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5913/// main file of the input.
5914void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5915 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005916 if (FD->isOverloadedOperator())
5917 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005918
Steve Narofffa15fd92008-10-28 20:29:00 +00005919 // Since function prototypes don't have ParmDecl's, we check the function
5920 // prototype. This enables us to rewrite function declarations and
5921 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005922 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005923
Sebastian Redld3a413d2009-04-26 20:35:05 +00005924 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005925 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005926 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005927 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005928 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005929 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005930 Body =
5931 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5932 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005933 CurrentBody = 0;
5934 if (PropParentMap) {
5935 delete PropParentMap;
5936 PropParentMap = 0;
5937 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005938 // This synthesizes and inserts the block "impl" struct, invoke function,
5939 // and any copy/dispose helper functions.
5940 InsertBlockLiteralsWithinFunction(FD);
5941 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005942 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005943 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005944 return;
5945 }
5946 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005947 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005948 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005949 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005950 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005951 Body =
5952 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5953 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005954 CurrentBody = 0;
5955 if (PropParentMap) {
5956 delete PropParentMap;
5957 PropParentMap = 0;
5958 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005959 InsertBlockLiteralsWithinMethod(MD);
5960 CurMethodDef = 0;
5961 }
5962 }
5963 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5964 ClassImplementation.push_back(CI);
5965 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5966 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005967 else if (isa<ObjCClassDecl>(D))
David Blaikieb219cfc2011-09-23 05:06:16 +00005968 llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005969 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5970 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005971 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005972 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005973 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005974 CheckFunctionPointerDecl(VD->getType(), VD);
5975 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005976 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005977 RewriteCastExpr(CE);
5978 }
5979 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005980 } else if (VD->getType()->isRecordType()) {
5981 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5982 if (RD->isDefinition())
5983 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005984 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005985 if (VD->getInit()) {
5986 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005987 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005988 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005989 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005990 CurrentBody = 0;
5991 if (PropParentMap) {
5992 delete PropParentMap;
5993 PropParentMap = 0;
5994 }
Mike Stump1eb44332009-09-09 15:08:12 +00005995 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005996 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005997 GlobalVarDecl = 0;
5998
5999 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00006000 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00006001 RewriteCastExpr(CE);
6002 }
6003 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006004 return;
6005 }
Richard Smith162e1c12011-04-15 14:24:37 +00006006 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00006007 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00006008 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00006009 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00006010 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
6011 return;
6012 }
6013 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00006014 if (RD->isDefinition())
6015 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00006016 return;
6017 }
6018 // Nothing yet.
6019}
6020
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00006021void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00006022 if (Diags.hasErrorOccurred())
6023 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006024
Steve Narofffa15fd92008-10-28 20:29:00 +00006025 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00006026
Steve Naroff621edce2009-04-29 16:37:50 +00006027 // Here's a great place to add any extra declarations that may be needed.
6028 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00006029 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00006030 E = ProtocolExprDecls.end(); I != E; ++I)
6031 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
6032
Benjamin Kramerd999b372010-02-14 14:14:16 +00006033 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00006034 if (ClassImplementation.size() || CategoryImplementation.size())
6035 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00006036
Steve Narofffa15fd92008-10-28 20:29:00 +00006037 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6038 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00006039 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00006040 Rewrite.getRewriteBufferFor(MainFileID)) {
6041 //printf("Changed:\n");
6042 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6043 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00006044 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00006045 }
Steve Narofface66252008-11-13 20:07:04 +00006046
Steve Naroff621edce2009-04-29 16:37:50 +00006047 if (ClassImplementation.size() || CategoryImplementation.size() ||
6048 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00006049 // Rewrite Objective-c meta data*
6050 std::string ResultStr;
6051 SynthesizeMetaDataIntoBuffer(ResultStr);
6052 // Emit metadata.
6053 *OutFile << ResultStr;
6054 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006055 OutFile->flush();
6056}