blob: b4da50583a18242a7a9b924fc292aedc98a221c4 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
106
107 /* Misc. containers needed for meta-data rewrite. */
108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000113 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000114 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000115 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
116 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
117
118 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
119 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
120
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000121 SmallVector<Stmt *, 32> Stmts;
122 SmallVector<int, 8> ObjCBcLabelNo;
123 // Remember all the @protocol(<expr>) expressions.
124 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
125
126 llvm::DenseSet<uint64_t> CopyDestroyCache;
127
128 // Block expressions.
129 SmallVector<BlockExpr *, 32> Blocks;
130 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
John McCallf4b88a42012-03-10 09:33:50 +0000133 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000134
135 // Block related declarations.
136 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
138 SmallVector<ValueDecl *, 8> BlockByRefDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
140 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
141 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
142 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
143
144 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000145 llvm::DenseMap<ObjCInterfaceDecl *,
146 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
147
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000148 // This maps an original source AST to it's rewritten form. This allows
149 // us to avoid rewriting the same node twice (which is very uncommon).
150 // This is needed to support some of the exotic property rewriting.
151 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
152
153 // Needed for header files being rewritten
154 bool IsHeader;
155 bool SilenceRewriteMacroWarning;
156 bool objc_impl_method;
157
158 bool DisableReplaceStmt;
159 class DisableReplaceStmtScope {
160 RewriteModernObjC &R;
161 bool SavedValue;
162
163 public:
164 DisableReplaceStmtScope(RewriteModernObjC &R)
165 : R(R), SavedValue(R.DisableReplaceStmt) {
166 R.DisableReplaceStmt = true;
167 }
168 ~DisableReplaceStmtScope() {
169 R.DisableReplaceStmt = SavedValue;
170 }
171 };
172 void InitializeCommon(ASTContext &context);
173
174 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000175 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000176 // Top Level Driver code.
177 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
178 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
179 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
180 if (!Class->isThisDeclarationADefinition()) {
181 RewriteForwardClassDecl(D);
182 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000183 } else {
184 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000185 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000186 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000187 }
188 }
189
190 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
191 if (!Proto->isThisDeclarationADefinition()) {
192 RewriteForwardProtocolDecl(D);
193 break;
194 }
195 }
196
197 HandleTopLevelSingleDecl(*I);
198 }
199 return true;
200 }
201 void HandleTopLevelSingleDecl(Decl *D);
202 void HandleDeclInMainFile(Decl *D);
203 RewriteModernObjC(std::string inFile, raw_ostream *OS,
204 DiagnosticsEngine &D, const LangOptions &LOpts,
205 bool silenceMacroWarn);
206
207 ~RewriteModernObjC() {}
208
209 virtual void HandleTranslationUnit(ASTContext &C);
210
211 void ReplaceStmt(Stmt *Old, Stmt *New) {
212 Stmt *ReplacingStmt = ReplacedNodes[Old];
213
214 if (ReplacingStmt)
215 return; // We can't rewrite the same node twice.
216
217 if (DisableReplaceStmt)
218 return;
219
220 // If replacement succeeded or warning disabled return with no warning.
221 if (!Rewrite.ReplaceStmt(Old, New)) {
222 ReplacedNodes[Old] = New;
223 return;
224 }
225 if (SilenceRewriteMacroWarning)
226 return;
227 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
228 << Old->getSourceRange();
229 }
230
231 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
232 if (DisableReplaceStmt)
233 return;
234
235 // Measure the old text.
236 int Size = Rewrite.getRangeSize(SrcRange);
237 if (Size == -1) {
238 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
239 << Old->getSourceRange();
240 return;
241 }
242 // Get the new text.
243 std::string SStr;
244 llvm::raw_string_ostream S(SStr);
245 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
246 const std::string &Str = S.str();
247
248 // If replacement succeeded or warning disabled return with no warning.
249 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
250 ReplacedNodes[Old] = New;
251 return;
252 }
253 if (SilenceRewriteMacroWarning)
254 return;
255 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
256 << Old->getSourceRange();
257 }
258
259 void InsertText(SourceLocation Loc, StringRef Str,
260 bool InsertAfter = true) {
261 // If insertion succeeded or warning disabled return with no warning.
262 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
263 SilenceRewriteMacroWarning)
264 return;
265
266 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
267 }
268
269 void ReplaceText(SourceLocation Start, unsigned OrigLength,
270 StringRef Str) {
271 // If removal succeeded or warning disabled return with no warning.
272 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
273 SilenceRewriteMacroWarning)
274 return;
275
276 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
277 }
278
279 // Syntactic Rewriting.
280 void RewriteRecordBody(RecordDecl *RD);
281 void RewriteInclude();
282 void RewriteForwardClassDecl(DeclGroupRef D);
283 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
284 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
285 const std::string &typedefString);
286 void RewriteImplementations();
287 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
288 ObjCImplementationDecl *IMD,
289 ObjCCategoryImplDecl *CID);
290 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
291 void RewriteImplementationDecl(Decl *Dcl);
292 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
293 ObjCMethodDecl *MDecl, std::string &ResultStr);
294 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
295 const FunctionType *&FPRetType);
296 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
297 ValueDecl *VD, bool def=false);
298 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
299 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
300 void RewriteForwardProtocolDecl(DeclGroupRef D);
301 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
302 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
303 void RewriteProperty(ObjCPropertyDecl *prop);
304 void RewriteFunctionDecl(FunctionDecl *FD);
305 void RewriteBlockPointerType(std::string& Str, QualType Type);
306 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000307 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
308 void RewriteTypeOfDecl(VarDecl *VD);
309 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
310
311 // Expression Rewriting.
312 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
313 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
314 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
317 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
318 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000319 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000320 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000321 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000322 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000323 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000324 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
325 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
326 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
327 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
328 SourceLocation OrigEnd);
329 Stmt *RewriteBreakStmt(BreakStmt *S);
330 Stmt *RewriteContinueStmt(ContinueStmt *S);
331 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000332 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000333 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000334
335 // Block rewriting.
336 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
337
338 // Block specific rewrite rules.
339 void RewriteBlockPointerDecl(NamedDecl *VD);
340 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000341 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000342 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
343 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
344
345 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
346 std::string &Result);
347
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000348 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
349
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000350 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
351
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000352 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
353 std::string &Result);
354
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000355 virtual void Initialize(ASTContext &context);
356
357 // Misc. AST transformation routines. Somtimes they end up calling
358 // rewriting routines on the new ASTs.
359 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
360 Expr **args, unsigned nargs,
361 SourceLocation StartLoc=SourceLocation(),
362 SourceLocation EndLoc=SourceLocation());
363
364 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
365 SourceLocation StartLoc=SourceLocation(),
366 SourceLocation EndLoc=SourceLocation());
367
368 void SynthCountByEnumWithState(std::string &buf);
369 void SynthMsgSendFunctionDecl();
370 void SynthMsgSendSuperFunctionDecl();
371 void SynthMsgSendStretFunctionDecl();
372 void SynthMsgSendFpretFunctionDecl();
373 void SynthMsgSendSuperStretFunctionDecl();
374 void SynthGetClassFunctionDecl();
375 void SynthGetMetaClassFunctionDecl();
376 void SynthGetSuperClassFunctionDecl();
377 void SynthSelGetUidFunctionDecl();
378 void SynthSuperContructorFunctionDecl();
379
380 // Rewriting metadata
381 template<typename MethodIterator>
382 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
383 MethodIterator MethodEnd,
384 bool IsInstanceMethod,
385 StringRef prefix,
386 StringRef ClassName,
387 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000388 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
389 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000390 virtual void RewriteObjCProtocolListMetaData(
391 const ObjCList<ObjCProtocolDecl> &Prots,
392 StringRef prefix, StringRef ClassName, std::string &Result);
393 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
394 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000395 virtual void RewriteClassSetupInitHook(std::string &Result);
396
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000397 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000398 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000399 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
400 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000401 virtual void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000402
403 // Rewriting ivar
404 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
405 std::string &Result);
406 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
407
408
409 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
410 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
411 StringRef funcName, std::string Tag);
412 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
413 StringRef funcName, std::string Tag);
414 std::string SynthesizeBlockImpl(BlockExpr *CE,
415 std::string Tag, std::string Desc);
416 std::string SynthesizeBlockDescriptor(std::string DescTag,
417 std::string ImplTag,
418 int i, StringRef funcName,
419 unsigned hasCopy);
420 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
421 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
422 StringRef FunName);
423 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
424 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000425 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000426
427 // Misc. helper routines.
428 QualType getProtocolType();
429 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000430 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
431 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
432 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
433
434 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
435 void CollectBlockDeclRefInfo(BlockExpr *Exp);
436 void GetBlockDeclRefExprs(Stmt *S);
437 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000438 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000439 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
440
441 // We avoid calling Type::isBlockPointerType(), since it operates on the
442 // canonical type. We only care if the top-level type is a closure pointer.
443 bool isTopLevelBlockPointerType(QualType T) {
444 return isa<BlockPointerType>(T);
445 }
446
447 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
448 /// to a function pointer type and upon success, returns true; false
449 /// otherwise.
450 bool convertBlockPointerToFunctionPointer(QualType &T) {
451 if (isTopLevelBlockPointerType(T)) {
452 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
453 T = Context->getPointerType(BPT->getPointeeType());
454 return true;
455 }
456 return false;
457 }
458
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000459 bool convertObjCTypeToCStyleType(QualType &T);
460
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000461 bool needToScanForQualifiers(QualType T);
462 QualType getSuperStructType();
463 QualType getConstantStringStructType();
464 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
465 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
466
467 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000468 if (T->isObjCQualifiedIdType()) {
469 bool isConst = T.isConstQualified();
470 T = isConst ? Context->getObjCIdType().withConst()
471 : Context->getObjCIdType();
472 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000473 else if (T->isObjCQualifiedClassType())
474 T = Context->getObjCClassType();
475 else if (T->isObjCObjectPointerType() &&
476 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
477 if (const ObjCObjectPointerType * OBJPT =
478 T->getAsObjCInterfacePointerType()) {
479 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
480 T = QualType(IFaceT, 0);
481 T = Context->getPointerType(T);
482 }
483 }
484 }
485
486 // FIXME: This predicate seems like it would be useful to add to ASTContext.
487 bool isObjCType(QualType T) {
488 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
489 return false;
490
491 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
492
493 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
494 OCT == Context->getCanonicalType(Context->getObjCClassType()))
495 return true;
496
497 if (const PointerType *PT = OCT->getAs<PointerType>()) {
498 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
499 PT->getPointeeType()->isObjCQualifiedIdType())
500 return true;
501 }
502 return false;
503 }
504 bool PointerTypeTakesAnyBlockArguments(QualType QT);
505 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
506 void GetExtentOfArgList(const char *Name, const char *&LParen,
507 const char *&RParen);
508
509 void QuoteDoublequotes(std::string &From, std::string &To) {
510 for (unsigned i = 0; i < From.length(); i++) {
511 if (From[i] == '"')
512 To += "\\\"";
513 else
514 To += From[i];
515 }
516 }
517
518 QualType getSimpleFunctionType(QualType result,
519 const QualType *args,
520 unsigned numArgs,
521 bool variadic = false) {
522 if (result == Context->getObjCInstanceType())
523 result = Context->getObjCIdType();
524 FunctionProtoType::ExtProtoInfo fpi;
525 fpi.Variadic = variadic;
526 return Context->getFunctionType(result, args, numArgs, fpi);
527 }
528
529 // Helper function: create a CStyleCastExpr with trivial type source info.
530 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
531 CastKind Kind, Expr *E) {
532 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
533 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
534 SourceLocation(), SourceLocation());
535 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000536
537 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
538 IdentifierInfo* II = &Context->Idents.get("load");
539 Selector LoadSel = Context->Selectors.getSelector(0, &II);
540 return OD->getClassMethod(LoadSel) != 0;
541 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000542 };
543
544}
545
546void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
547 NamedDecl *D) {
548 if (const FunctionProtoType *fproto
549 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
550 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
551 E = fproto->arg_type_end(); I && (I != E); ++I)
552 if (isTopLevelBlockPointerType(*I)) {
553 // All the args are checked/rewritten. Don't call twice!
554 RewriteBlockPointerDecl(D);
555 break;
556 }
557 }
558}
559
560void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
561 const PointerType *PT = funcType->getAs<PointerType>();
562 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
563 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
564}
565
566static bool IsHeaderFile(const std::string &Filename) {
567 std::string::size_type DotPos = Filename.rfind('.');
568
569 if (DotPos == std::string::npos) {
570 // no file extension
571 return false;
572 }
573
574 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
575 // C header: .h
576 // C++ header: .hh or .H;
577 return Ext == "h" || Ext == "hh" || Ext == "H";
578}
579
580RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
581 DiagnosticsEngine &D, const LangOptions &LOpts,
582 bool silenceMacroWarn)
583 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
584 SilenceRewriteMacroWarning(silenceMacroWarn) {
585 IsHeader = IsHeaderFile(inFile);
586 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
587 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000588 // FIXME. This should be an error. But if block is not called, it is OK. And it
589 // may break including some headers.
590 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
591 "rewriting block literal declared in global scope is not implemented");
592
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000593 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
594 DiagnosticsEngine::Warning,
595 "rewriter doesn't support user-specified control flow semantics "
596 "for @try/@finally (code may not execute properly)");
597}
598
599ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
600 raw_ostream* OS,
601 DiagnosticsEngine &Diags,
602 const LangOptions &LOpts,
603 bool SilenceRewriteMacroWarning) {
604 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
605}
606
607void RewriteModernObjC::InitializeCommon(ASTContext &context) {
608 Context = &context;
609 SM = &Context->getSourceManager();
610 TUDecl = Context->getTranslationUnitDecl();
611 MsgSendFunctionDecl = 0;
612 MsgSendSuperFunctionDecl = 0;
613 MsgSendStretFunctionDecl = 0;
614 MsgSendSuperStretFunctionDecl = 0;
615 MsgSendFpretFunctionDecl = 0;
616 GetClassFunctionDecl = 0;
617 GetMetaClassFunctionDecl = 0;
618 GetSuperClassFunctionDecl = 0;
619 SelGetUidFunctionDecl = 0;
620 CFStringFunctionDecl = 0;
621 ConstantStringClassReference = 0;
622 NSStringRecord = 0;
623 CurMethodDef = 0;
624 CurFunctionDef = 0;
625 CurFunctionDeclToDeclareForBlock = 0;
626 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000627 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000628 SuperStructDecl = 0;
629 ProtocolTypeDecl = 0;
630 ConstantStringDecl = 0;
631 BcLabelCount = 0;
632 SuperContructorFunctionDecl = 0;
633 NumObjCStringLiterals = 0;
634 PropParentMap = 0;
635 CurrentBody = 0;
636 DisableReplaceStmt = false;
637 objc_impl_method = false;
638
639 // Get the ID and start/end of the main file.
640 MainFileID = SM->getMainFileID();
641 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
642 MainFileStart = MainBuf->getBufferStart();
643 MainFileEnd = MainBuf->getBufferEnd();
644
David Blaikie4e4d0842012-03-11 07:00:24 +0000645 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000646}
647
648//===----------------------------------------------------------------------===//
649// Top Level Driver Code
650//===----------------------------------------------------------------------===//
651
652void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
653 if (Diags.hasErrorOccurred())
654 return;
655
656 // Two cases: either the decl could be in the main file, or it could be in a
657 // #included file. If the former, rewrite it now. If the later, check to see
658 // if we rewrote the #include/#import.
659 SourceLocation Loc = D->getLocation();
660 Loc = SM->getExpansionLoc(Loc);
661
662 // If this is for a builtin, ignore it.
663 if (Loc.isInvalid()) return;
664
665 // Look for built-in declarations that we need to refer during the rewrite.
666 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
667 RewriteFunctionDecl(FD);
668 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
669 // declared in <Foundation/NSString.h>
670 if (FVD->getName() == "_NSConstantStringClassReference") {
671 ConstantStringClassReference = FVD;
672 return;
673 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000674 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
675 RewriteCategoryDecl(CD);
676 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
677 if (PD->isThisDeclarationADefinition())
678 RewriteProtocolDecl(PD);
679 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000680 // FIXME. This will not work in all situations and leaving it out
681 // is harmless.
682 // RewriteLinkageSpec(LSD);
683
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000684 // Recurse into linkage specifications
685 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
686 DIEnd = LSD->decls_end();
687 DI != DIEnd; ) {
688 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
689 if (!IFace->isThisDeclarationADefinition()) {
690 SmallVector<Decl *, 8> DG;
691 SourceLocation StartLoc = IFace->getLocStart();
692 do {
693 if (isa<ObjCInterfaceDecl>(*DI) &&
694 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
695 StartLoc == (*DI)->getLocStart())
696 DG.push_back(*DI);
697 else
698 break;
699
700 ++DI;
701 } while (DI != DIEnd);
702 RewriteForwardClassDecl(DG);
703 continue;
704 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000705 else {
706 // Keep track of all interface declarations seen.
707 ObjCInterfacesSeen.push_back(IFace);
708 ++DI;
709 continue;
710 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000711 }
712
713 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
714 if (!Proto->isThisDeclarationADefinition()) {
715 SmallVector<Decl *, 8> DG;
716 SourceLocation StartLoc = Proto->getLocStart();
717 do {
718 if (isa<ObjCProtocolDecl>(*DI) &&
719 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
720 StartLoc == (*DI)->getLocStart())
721 DG.push_back(*DI);
722 else
723 break;
724
725 ++DI;
726 } while (DI != DIEnd);
727 RewriteForwardProtocolDecl(DG);
728 continue;
729 }
730 }
731
732 HandleTopLevelSingleDecl(*DI);
733 ++DI;
734 }
735 }
736 // If we have a decl in the main file, see if we should rewrite it.
737 if (SM->isFromMainFile(Loc))
738 return HandleDeclInMainFile(D);
739}
740
741//===----------------------------------------------------------------------===//
742// Syntactic (non-AST) Rewriting Code
743//===----------------------------------------------------------------------===//
744
745void RewriteModernObjC::RewriteInclude() {
746 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
747 StringRef MainBuf = SM->getBufferData(MainFileID);
748 const char *MainBufStart = MainBuf.begin();
749 const char *MainBufEnd = MainBuf.end();
750 size_t ImportLen = strlen("import");
751
752 // Loop over the whole file, looking for includes.
753 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
754 if (*BufPtr == '#') {
755 if (++BufPtr == MainBufEnd)
756 return;
757 while (*BufPtr == ' ' || *BufPtr == '\t')
758 if (++BufPtr == MainBufEnd)
759 return;
760 if (!strncmp(BufPtr, "import", ImportLen)) {
761 // replace import with include
762 SourceLocation ImportLoc =
763 LocStart.getLocWithOffset(BufPtr-MainBufStart);
764 ReplaceText(ImportLoc, ImportLen, "include");
765 BufPtr += ImportLen;
766 }
767 }
768 }
769}
770
771static std::string getIvarAccessString(ObjCIvarDecl *OID) {
772 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
773 std::string S;
774 S = "((struct ";
775 S += ClassDecl->getIdentifier()->getName();
776 S += "_IMPL *)self)->";
777 S += OID->getName();
778 return S;
779}
780
781void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
782 ObjCImplementationDecl *IMD,
783 ObjCCategoryImplDecl *CID) {
784 static bool objcGetPropertyDefined = false;
785 static bool objcSetPropertyDefined = false;
786 SourceLocation startLoc = PID->getLocStart();
787 InsertText(startLoc, "// ");
788 const char *startBuf = SM->getCharacterData(startLoc);
789 assert((*startBuf == '@') && "bogus @synthesize location");
790 const char *semiBuf = strchr(startBuf, ';');
791 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
792 SourceLocation onePastSemiLoc =
793 startLoc.getLocWithOffset(semiBuf-startBuf+1);
794
795 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
796 return; // FIXME: is this correct?
797
798 // Generate the 'getter' function.
799 ObjCPropertyDecl *PD = PID->getPropertyDecl();
800 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
801
802 if (!OID)
803 return;
804 unsigned Attributes = PD->getPropertyAttributes();
805 if (!PD->getGetterMethodDecl()->isDefined()) {
806 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
807 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
808 ObjCPropertyDecl::OBJC_PR_copy));
809 std::string Getr;
810 if (GenGetProperty && !objcGetPropertyDefined) {
811 objcGetPropertyDefined = true;
812 // FIXME. Is this attribute correct in all cases?
813 Getr = "\nextern \"C\" __declspec(dllimport) "
814 "id objc_getProperty(id, SEL, long, bool);\n";
815 }
816 RewriteObjCMethodDecl(OID->getContainingInterface(),
817 PD->getGetterMethodDecl(), Getr);
818 Getr += "{ ";
819 // Synthesize an explicit cast to gain access to the ivar.
820 // See objc-act.c:objc_synthesize_new_getter() for details.
821 if (GenGetProperty) {
822 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
823 Getr += "typedef ";
824 const FunctionType *FPRetType = 0;
825 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
826 FPRetType);
827 Getr += " _TYPE";
828 if (FPRetType) {
829 Getr += ")"; // close the precedence "scope" for "*".
830
831 // Now, emit the argument types (if any).
832 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
833 Getr += "(";
834 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
835 if (i) Getr += ", ";
836 std::string ParamStr = FT->getArgType(i).getAsString(
837 Context->getPrintingPolicy());
838 Getr += ParamStr;
839 }
840 if (FT->isVariadic()) {
841 if (FT->getNumArgs()) Getr += ", ";
842 Getr += "...";
843 }
844 Getr += ")";
845 } else
846 Getr += "()";
847 }
848 Getr += ";\n";
849 Getr += "return (_TYPE)";
850 Getr += "objc_getProperty(self, _cmd, ";
851 RewriteIvarOffsetComputation(OID, Getr);
852 Getr += ", 1)";
853 }
854 else
855 Getr += "return " + getIvarAccessString(OID);
856 Getr += "; }";
857 InsertText(onePastSemiLoc, Getr);
858 }
859
860 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
861 return;
862
863 // Generate the 'setter' function.
864 std::string Setr;
865 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
866 ObjCPropertyDecl::OBJC_PR_copy);
867 if (GenSetProperty && !objcSetPropertyDefined) {
868 objcSetPropertyDefined = true;
869 // FIXME. Is this attribute correct in all cases?
870 Setr = "\nextern \"C\" __declspec(dllimport) "
871 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
872 }
873
874 RewriteObjCMethodDecl(OID->getContainingInterface(),
875 PD->getSetterMethodDecl(), Setr);
876 Setr += "{ ";
877 // Synthesize an explicit cast to initialize the ivar.
878 // See objc-act.c:objc_synthesize_new_setter() for details.
879 if (GenSetProperty) {
880 Setr += "objc_setProperty (self, _cmd, ";
881 RewriteIvarOffsetComputation(OID, Setr);
882 Setr += ", (id)";
883 Setr += PD->getName();
884 Setr += ", ";
885 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
886 Setr += "0, ";
887 else
888 Setr += "1, ";
889 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
890 Setr += "1)";
891 else
892 Setr += "0)";
893 }
894 else {
895 Setr += getIvarAccessString(OID) + " = ";
896 Setr += PD->getName();
897 }
898 Setr += "; }";
899 InsertText(onePastSemiLoc, Setr);
900}
901
902static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
903 std::string &typedefString) {
904 typedefString += "#ifndef _REWRITER_typedef_";
905 typedefString += ForwardDecl->getNameAsString();
906 typedefString += "\n";
907 typedefString += "#define _REWRITER_typedef_";
908 typedefString += ForwardDecl->getNameAsString();
909 typedefString += "\n";
910 typedefString += "typedef struct objc_object ";
911 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000912 // typedef struct { } _objc_exc_Classname;
913 typedefString += ";\ntypedef struct {} _objc_exc_";
914 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000915 typedefString += ";\n#endif\n";
916}
917
918void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
919 const std::string &typedefString) {
920 SourceLocation startLoc = ClassDecl->getLocStart();
921 const char *startBuf = SM->getCharacterData(startLoc);
922 const char *semiPtr = strchr(startBuf, ';');
923 // Replace the @class with typedefs corresponding to the classes.
924 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
925}
926
927void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
928 std::string typedefString;
929 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
930 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
931 if (I == D.begin()) {
932 // Translate to typedef's that forward reference structs with the same name
933 // as the class. As a convenience, we include the original declaration
934 // as a comment.
935 typedefString += "// @class ";
936 typedefString += ForwardDecl->getNameAsString();
937 typedefString += ";\n";
938 }
939 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
940 }
941 DeclGroupRef::iterator I = D.begin();
942 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
943}
944
945void RewriteModernObjC::RewriteForwardClassDecl(
946 const llvm::SmallVector<Decl*, 8> &D) {
947 std::string typedefString;
948 for (unsigned i = 0; i < D.size(); i++) {
949 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
950 if (i == 0) {
951 typedefString += "// @class ";
952 typedefString += ForwardDecl->getNameAsString();
953 typedefString += ";\n";
954 }
955 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
956 }
957 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
958}
959
960void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
961 // When method is a synthesized one, such as a getter/setter there is
962 // nothing to rewrite.
963 if (Method->isImplicit())
964 return;
965 SourceLocation LocStart = Method->getLocStart();
966 SourceLocation LocEnd = Method->getLocEnd();
967
968 if (SM->getExpansionLineNumber(LocEnd) >
969 SM->getExpansionLineNumber(LocStart)) {
970 InsertText(LocStart, "#if 0\n");
971 ReplaceText(LocEnd, 1, ";\n#endif\n");
972 } else {
973 InsertText(LocStart, "// ");
974 }
975}
976
977void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
978 SourceLocation Loc = prop->getAtLoc();
979
980 ReplaceText(Loc, 0, "// ");
981 // FIXME: handle properties that are declared across multiple lines.
982}
983
984void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
985 SourceLocation LocStart = CatDecl->getLocStart();
986
987 // FIXME: handle category headers that are declared across multiple lines.
988 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000989 if (CatDecl->getIvarLBraceLoc().isValid())
990 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000991 for (ObjCCategoryDecl::ivar_iterator
992 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
993 ObjCIvarDecl *Ivar = (*I);
994 SourceLocation LocStart = Ivar->getLocStart();
995 ReplaceText(LocStart, 0, "// ");
996 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000997 if (CatDecl->getIvarRBraceLoc().isValid())
998 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
999
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001000 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1001 E = CatDecl->prop_end(); I != E; ++I)
1002 RewriteProperty(*I);
1003
1004 for (ObjCCategoryDecl::instmeth_iterator
1005 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1006 I != E; ++I)
1007 RewriteMethodDeclaration(*I);
1008 for (ObjCCategoryDecl::classmeth_iterator
1009 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1010 I != E; ++I)
1011 RewriteMethodDeclaration(*I);
1012
1013 // Lastly, comment out the @end.
1014 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1015 strlen("@end"), "/* @end */");
1016}
1017
1018void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1019 SourceLocation LocStart = PDecl->getLocStart();
1020 assert(PDecl->isThisDeclarationADefinition());
1021
1022 // FIXME: handle protocol headers that are declared across multiple lines.
1023 ReplaceText(LocStart, 0, "// ");
1024
1025 for (ObjCProtocolDecl::instmeth_iterator
1026 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1027 I != E; ++I)
1028 RewriteMethodDeclaration(*I);
1029 for (ObjCProtocolDecl::classmeth_iterator
1030 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1031 I != E; ++I)
1032 RewriteMethodDeclaration(*I);
1033
1034 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1035 E = PDecl->prop_end(); I != E; ++I)
1036 RewriteProperty(*I);
1037
1038 // Lastly, comment out the @end.
1039 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1040 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1041
1042 // Must comment out @optional/@required
1043 const char *startBuf = SM->getCharacterData(LocStart);
1044 const char *endBuf = SM->getCharacterData(LocEnd);
1045 for (const char *p = startBuf; p < endBuf; p++) {
1046 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1047 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1048 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1049
1050 }
1051 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1052 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1053 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1054
1055 }
1056 }
1057}
1058
1059void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1060 SourceLocation LocStart = (*D.begin())->getLocStart();
1061 if (LocStart.isInvalid())
1062 llvm_unreachable("Invalid SourceLocation");
1063 // FIXME: handle forward protocol that are declared across multiple lines.
1064 ReplaceText(LocStart, 0, "// ");
1065}
1066
1067void
1068RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1069 SourceLocation LocStart = DG[0]->getLocStart();
1070 if (LocStart.isInvalid())
1071 llvm_unreachable("Invalid SourceLocation");
1072 // FIXME: handle forward protocol that are declared across multiple lines.
1073 ReplaceText(LocStart, 0, "// ");
1074}
1075
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001076void
1077RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1078 SourceLocation LocStart = LSD->getExternLoc();
1079 if (LocStart.isInvalid())
1080 llvm_unreachable("Invalid extern SourceLocation");
1081
1082 ReplaceText(LocStart, 0, "// ");
1083 if (!LSD->hasBraces())
1084 return;
1085 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1086 SourceLocation LocRBrace = LSD->getRBraceLoc();
1087 if (LocRBrace.isInvalid())
1088 llvm_unreachable("Invalid rbrace SourceLocation");
1089 ReplaceText(LocRBrace, 0, "// ");
1090}
1091
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001092void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1093 const FunctionType *&FPRetType) {
1094 if (T->isObjCQualifiedIdType())
1095 ResultStr += "id";
1096 else if (T->isFunctionPointerType() ||
1097 T->isBlockPointerType()) {
1098 // needs special handling, since pointer-to-functions have special
1099 // syntax (where a decaration models use).
1100 QualType retType = T;
1101 QualType PointeeTy;
1102 if (const PointerType* PT = retType->getAs<PointerType>())
1103 PointeeTy = PT->getPointeeType();
1104 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1105 PointeeTy = BPT->getPointeeType();
1106 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1107 ResultStr += FPRetType->getResultType().getAsString(
1108 Context->getPrintingPolicy());
1109 ResultStr += "(*";
1110 }
1111 } else
1112 ResultStr += T.getAsString(Context->getPrintingPolicy());
1113}
1114
1115void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1116 ObjCMethodDecl *OMD,
1117 std::string &ResultStr) {
1118 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1119 const FunctionType *FPRetType = 0;
1120 ResultStr += "\nstatic ";
1121 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1122 ResultStr += " ";
1123
1124 // Unique method name
1125 std::string NameStr;
1126
1127 if (OMD->isInstanceMethod())
1128 NameStr += "_I_";
1129 else
1130 NameStr += "_C_";
1131
1132 NameStr += IDecl->getNameAsString();
1133 NameStr += "_";
1134
1135 if (ObjCCategoryImplDecl *CID =
1136 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1137 NameStr += CID->getNameAsString();
1138 NameStr += "_";
1139 }
1140 // Append selector names, replacing ':' with '_'
1141 {
1142 std::string selString = OMD->getSelector().getAsString();
1143 int len = selString.size();
1144 for (int i = 0; i < len; i++)
1145 if (selString[i] == ':')
1146 selString[i] = '_';
1147 NameStr += selString;
1148 }
1149 // Remember this name for metadata emission
1150 MethodInternalNames[OMD] = NameStr;
1151 ResultStr += NameStr;
1152
1153 // Rewrite arguments
1154 ResultStr += "(";
1155
1156 // invisible arguments
1157 if (OMD->isInstanceMethod()) {
1158 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1159 selfTy = Context->getPointerType(selfTy);
1160 if (!LangOpts.MicrosoftExt) {
1161 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1162 ResultStr += "struct ";
1163 }
1164 // When rewriting for Microsoft, explicitly omit the structure name.
1165 ResultStr += IDecl->getNameAsString();
1166 ResultStr += " *";
1167 }
1168 else
1169 ResultStr += Context->getObjCClassType().getAsString(
1170 Context->getPrintingPolicy());
1171
1172 ResultStr += " self, ";
1173 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1174 ResultStr += " _cmd";
1175
1176 // Method arguments.
1177 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1178 E = OMD->param_end(); PI != E; ++PI) {
1179 ParmVarDecl *PDecl = *PI;
1180 ResultStr += ", ";
1181 if (PDecl->getType()->isObjCQualifiedIdType()) {
1182 ResultStr += "id ";
1183 ResultStr += PDecl->getNameAsString();
1184 } else {
1185 std::string Name = PDecl->getNameAsString();
1186 QualType QT = PDecl->getType();
1187 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001188 (void)convertBlockPointerToFunctionPointer(QT);
1189 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001190 ResultStr += Name;
1191 }
1192 }
1193 if (OMD->isVariadic())
1194 ResultStr += ", ...";
1195 ResultStr += ") ";
1196
1197 if (FPRetType) {
1198 ResultStr += ")"; // close the precedence "scope" for "*".
1199
1200 // Now, emit the argument types (if any).
1201 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1202 ResultStr += "(";
1203 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1204 if (i) ResultStr += ", ";
1205 std::string ParamStr = FT->getArgType(i).getAsString(
1206 Context->getPrintingPolicy());
1207 ResultStr += ParamStr;
1208 }
1209 if (FT->isVariadic()) {
1210 if (FT->getNumArgs()) ResultStr += ", ";
1211 ResultStr += "...";
1212 }
1213 ResultStr += ")";
1214 } else {
1215 ResultStr += "()";
1216 }
1217 }
1218}
1219void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1220 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1221 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1222
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001223 if (IMD) {
1224 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001225 if (IMD->getIvarLBraceLoc().isValid())
1226 InsertText(IMD->getIvarLBraceLoc(), "// ");
1227 for (ObjCImplementationDecl::ivar_iterator
1228 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1229 ObjCIvarDecl *Ivar = (*I);
1230 SourceLocation LocStart = Ivar->getLocStart();
1231 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001232 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001233 if (IMD->getIvarRBraceLoc().isValid())
1234 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001235 }
1236 else
1237 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001238
1239 for (ObjCCategoryImplDecl::instmeth_iterator
1240 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1241 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1242 I != E; ++I) {
1243 std::string ResultStr;
1244 ObjCMethodDecl *OMD = *I;
1245 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1246 SourceLocation LocStart = OMD->getLocStart();
1247 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1248
1249 const char *startBuf = SM->getCharacterData(LocStart);
1250 const char *endBuf = SM->getCharacterData(LocEnd);
1251 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1252 }
1253
1254 for (ObjCCategoryImplDecl::classmeth_iterator
1255 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1256 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1257 I != E; ++I) {
1258 std::string ResultStr;
1259 ObjCMethodDecl *OMD = *I;
1260 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1261 SourceLocation LocStart = OMD->getLocStart();
1262 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1263
1264 const char *startBuf = SM->getCharacterData(LocStart);
1265 const char *endBuf = SM->getCharacterData(LocEnd);
1266 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1267 }
1268 for (ObjCCategoryImplDecl::propimpl_iterator
1269 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1270 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1271 I != E; ++I) {
1272 RewritePropertyImplDecl(*I, IMD, CID);
1273 }
1274
1275 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1276}
1277
1278void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001279 // Do not synthesize more than once.
1280 if (ObjCSynthesizedStructs.count(ClassDecl))
1281 return;
1282 // Make sure super class's are written before current class is written.
1283 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1284 while (SuperClass) {
1285 RewriteInterfaceDecl(SuperClass);
1286 SuperClass = SuperClass->getSuperClass();
1287 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001288 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001289 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001290 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001291 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001292 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1293
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001294 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001295 // Mark this typedef as having been written into its c++ equivalent.
1296 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001297
1298 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001299 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001300 RewriteProperty(*I);
1301 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001302 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001303 I != E; ++I)
1304 RewriteMethodDeclaration(*I);
1305 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001306 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001307 I != E; ++I)
1308 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001309
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001310 // Lastly, comment out the @end.
1311 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1312 "/* @end */");
1313 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001314}
1315
1316Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1317 SourceRange OldRange = PseudoOp->getSourceRange();
1318
1319 // We just magically know some things about the structure of this
1320 // expression.
1321 ObjCMessageExpr *OldMsg =
1322 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1323 PseudoOp->getNumSemanticExprs() - 1));
1324
1325 // Because the rewriter doesn't allow us to rewrite rewritten code,
1326 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001327 Expr *Base;
1328 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001329 {
1330 DisableReplaceStmtScope S(*this);
1331
1332 // Rebuild the base expression if we have one.
1333 Base = 0;
1334 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1335 Base = OldMsg->getInstanceReceiver();
1336 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1337 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1338 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001339
1340 unsigned numArgs = OldMsg->getNumArgs();
1341 for (unsigned i = 0; i < numArgs; i++) {
1342 Expr *Arg = OldMsg->getArg(i);
1343 if (isa<OpaqueValueExpr>(Arg))
1344 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1345 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1346 Args.push_back(Arg);
1347 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001348 }
1349
1350 // TODO: avoid this copy.
1351 SmallVector<SourceLocation, 1> SelLocs;
1352 OldMsg->getSelectorLocs(SelLocs);
1353
1354 ObjCMessageExpr *NewMsg = 0;
1355 switch (OldMsg->getReceiverKind()) {
1356 case ObjCMessageExpr::Class:
1357 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1358 OldMsg->getValueKind(),
1359 OldMsg->getLeftLoc(),
1360 OldMsg->getClassReceiverTypeInfo(),
1361 OldMsg->getSelector(),
1362 SelLocs,
1363 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001364 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001365 OldMsg->getRightLoc(),
1366 OldMsg->isImplicit());
1367 break;
1368
1369 case ObjCMessageExpr::Instance:
1370 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1371 OldMsg->getValueKind(),
1372 OldMsg->getLeftLoc(),
1373 Base,
1374 OldMsg->getSelector(),
1375 SelLocs,
1376 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001377 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001378 OldMsg->getRightLoc(),
1379 OldMsg->isImplicit());
1380 break;
1381
1382 case ObjCMessageExpr::SuperClass:
1383 case ObjCMessageExpr::SuperInstance:
1384 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1385 OldMsg->getValueKind(),
1386 OldMsg->getLeftLoc(),
1387 OldMsg->getSuperLoc(),
1388 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1389 OldMsg->getSuperType(),
1390 OldMsg->getSelector(),
1391 SelLocs,
1392 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001393 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001394 OldMsg->getRightLoc(),
1395 OldMsg->isImplicit());
1396 break;
1397 }
1398
1399 Stmt *Replacement = SynthMessageExpr(NewMsg);
1400 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1401 return Replacement;
1402}
1403
1404Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1405 SourceRange OldRange = PseudoOp->getSourceRange();
1406
1407 // We just magically know some things about the structure of this
1408 // expression.
1409 ObjCMessageExpr *OldMsg =
1410 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1411
1412 // Because the rewriter doesn't allow us to rewrite rewritten code,
1413 // we need to suppress rewriting the sub-statements.
1414 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001415 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001416 {
1417 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001418 // Rebuild the base expression if we have one.
1419 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1420 Base = OldMsg->getInstanceReceiver();
1421 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1422 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1423 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001424 unsigned numArgs = OldMsg->getNumArgs();
1425 for (unsigned i = 0; i < numArgs; i++) {
1426 Expr *Arg = OldMsg->getArg(i);
1427 if (isa<OpaqueValueExpr>(Arg))
1428 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1429 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1430 Args.push_back(Arg);
1431 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001432 }
1433
1434 // Intentionally empty.
1435 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001436
1437 ObjCMessageExpr *NewMsg = 0;
1438 switch (OldMsg->getReceiverKind()) {
1439 case ObjCMessageExpr::Class:
1440 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1441 OldMsg->getValueKind(),
1442 OldMsg->getLeftLoc(),
1443 OldMsg->getClassReceiverTypeInfo(),
1444 OldMsg->getSelector(),
1445 SelLocs,
1446 OldMsg->getMethodDecl(),
1447 Args,
1448 OldMsg->getRightLoc(),
1449 OldMsg->isImplicit());
1450 break;
1451
1452 case ObjCMessageExpr::Instance:
1453 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1454 OldMsg->getValueKind(),
1455 OldMsg->getLeftLoc(),
1456 Base,
1457 OldMsg->getSelector(),
1458 SelLocs,
1459 OldMsg->getMethodDecl(),
1460 Args,
1461 OldMsg->getRightLoc(),
1462 OldMsg->isImplicit());
1463 break;
1464
1465 case ObjCMessageExpr::SuperClass:
1466 case ObjCMessageExpr::SuperInstance:
1467 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1468 OldMsg->getValueKind(),
1469 OldMsg->getLeftLoc(),
1470 OldMsg->getSuperLoc(),
1471 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1472 OldMsg->getSuperType(),
1473 OldMsg->getSelector(),
1474 SelLocs,
1475 OldMsg->getMethodDecl(),
1476 Args,
1477 OldMsg->getRightLoc(),
1478 OldMsg->isImplicit());
1479 break;
1480 }
1481
1482 Stmt *Replacement = SynthMessageExpr(NewMsg);
1483 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1484 return Replacement;
1485}
1486
1487/// SynthCountByEnumWithState - To print:
1488/// ((unsigned int (*)
1489/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1490/// (void *)objc_msgSend)((id)l_collection,
1491/// sel_registerName(
1492/// "countByEnumeratingWithState:objects:count:"),
1493/// &enumState,
1494/// (id *)__rw_items, (unsigned int)16)
1495///
1496void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1497 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1498 "id *, unsigned int))(void *)objc_msgSend)";
1499 buf += "\n\t\t";
1500 buf += "((id)l_collection,\n\t\t";
1501 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1502 buf += "\n\t\t";
1503 buf += "&enumState, "
1504 "(id *)__rw_items, (unsigned int)16)";
1505}
1506
1507/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1508/// statement to exit to its outer synthesized loop.
1509///
1510Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1511 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1512 return S;
1513 // replace break with goto __break_label
1514 std::string buf;
1515
1516 SourceLocation startLoc = S->getLocStart();
1517 buf = "goto __break_label_";
1518 buf += utostr(ObjCBcLabelNo.back());
1519 ReplaceText(startLoc, strlen("break"), buf);
1520
1521 return 0;
1522}
1523
1524/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1525/// statement to continue with its inner synthesized loop.
1526///
1527Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1528 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1529 return S;
1530 // replace continue with goto __continue_label
1531 std::string buf;
1532
1533 SourceLocation startLoc = S->getLocStart();
1534 buf = "goto __continue_label_";
1535 buf += utostr(ObjCBcLabelNo.back());
1536 ReplaceText(startLoc, strlen("continue"), buf);
1537
1538 return 0;
1539}
1540
1541/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1542/// It rewrites:
1543/// for ( type elem in collection) { stmts; }
1544
1545/// Into:
1546/// {
1547/// type elem;
1548/// struct __objcFastEnumerationState enumState = { 0 };
1549/// id __rw_items[16];
1550/// id l_collection = (id)collection;
1551/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1552/// objects:__rw_items count:16];
1553/// if (limit) {
1554/// unsigned long startMutations = *enumState.mutationsPtr;
1555/// do {
1556/// unsigned long counter = 0;
1557/// do {
1558/// if (startMutations != *enumState.mutationsPtr)
1559/// objc_enumerationMutation(l_collection);
1560/// elem = (type)enumState.itemsPtr[counter++];
1561/// stmts;
1562/// __continue_label: ;
1563/// } while (counter < limit);
1564/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1565/// objects:__rw_items count:16]);
1566/// elem = nil;
1567/// __break_label: ;
1568/// }
1569/// else
1570/// elem = nil;
1571/// }
1572///
1573Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1574 SourceLocation OrigEnd) {
1575 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1576 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1577 "ObjCForCollectionStmt Statement stack mismatch");
1578 assert(!ObjCBcLabelNo.empty() &&
1579 "ObjCForCollectionStmt - Label No stack empty");
1580
1581 SourceLocation startLoc = S->getLocStart();
1582 const char *startBuf = SM->getCharacterData(startLoc);
1583 StringRef elementName;
1584 std::string elementTypeAsString;
1585 std::string buf;
1586 buf = "\n{\n\t";
1587 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1588 // type elem;
1589 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1590 QualType ElementType = cast<ValueDecl>(D)->getType();
1591 if (ElementType->isObjCQualifiedIdType() ||
1592 ElementType->isObjCQualifiedInterfaceType())
1593 // Simply use 'id' for all qualified types.
1594 elementTypeAsString = "id";
1595 else
1596 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1597 buf += elementTypeAsString;
1598 buf += " ";
1599 elementName = D->getName();
1600 buf += elementName;
1601 buf += ";\n\t";
1602 }
1603 else {
1604 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1605 elementName = DR->getDecl()->getName();
1606 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1607 if (VD->getType()->isObjCQualifiedIdType() ||
1608 VD->getType()->isObjCQualifiedInterfaceType())
1609 // Simply use 'id' for all qualified types.
1610 elementTypeAsString = "id";
1611 else
1612 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1613 }
1614
1615 // struct __objcFastEnumerationState enumState = { 0 };
1616 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1617 // id __rw_items[16];
1618 buf += "id __rw_items[16];\n\t";
1619 // id l_collection = (id)
1620 buf += "id l_collection = (id)";
1621 // Find start location of 'collection' the hard way!
1622 const char *startCollectionBuf = startBuf;
1623 startCollectionBuf += 3; // skip 'for'
1624 startCollectionBuf = strchr(startCollectionBuf, '(');
1625 startCollectionBuf++; // skip '('
1626 // find 'in' and skip it.
1627 while (*startCollectionBuf != ' ' ||
1628 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1629 (*(startCollectionBuf+3) != ' ' &&
1630 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1631 startCollectionBuf++;
1632 startCollectionBuf += 3;
1633
1634 // Replace: "for (type element in" with string constructed thus far.
1635 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1636 // Replace ')' in for '(' type elem in collection ')' with ';'
1637 SourceLocation rightParenLoc = S->getRParenLoc();
1638 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1639 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1640 buf = ";\n\t";
1641
1642 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1643 // objects:__rw_items count:16];
1644 // which is synthesized into:
1645 // unsigned int limit =
1646 // ((unsigned int (*)
1647 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1648 // (void *)objc_msgSend)((id)l_collection,
1649 // sel_registerName(
1650 // "countByEnumeratingWithState:objects:count:"),
1651 // (struct __objcFastEnumerationState *)&state,
1652 // (id *)__rw_items, (unsigned int)16);
1653 buf += "unsigned long limit =\n\t\t";
1654 SynthCountByEnumWithState(buf);
1655 buf += ";\n\t";
1656 /// if (limit) {
1657 /// unsigned long startMutations = *enumState.mutationsPtr;
1658 /// do {
1659 /// unsigned long counter = 0;
1660 /// do {
1661 /// if (startMutations != *enumState.mutationsPtr)
1662 /// objc_enumerationMutation(l_collection);
1663 /// elem = (type)enumState.itemsPtr[counter++];
1664 buf += "if (limit) {\n\t";
1665 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1666 buf += "do {\n\t\t";
1667 buf += "unsigned long counter = 0;\n\t\t";
1668 buf += "do {\n\t\t\t";
1669 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1670 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1671 buf += elementName;
1672 buf += " = (";
1673 buf += elementTypeAsString;
1674 buf += ")enumState.itemsPtr[counter++];";
1675 // Replace ')' in for '(' type elem in collection ')' with all of these.
1676 ReplaceText(lparenLoc, 1, buf);
1677
1678 /// __continue_label: ;
1679 /// } while (counter < limit);
1680 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1681 /// objects:__rw_items count:16]);
1682 /// elem = nil;
1683 /// __break_label: ;
1684 /// }
1685 /// else
1686 /// elem = nil;
1687 /// }
1688 ///
1689 buf = ";\n\t";
1690 buf += "__continue_label_";
1691 buf += utostr(ObjCBcLabelNo.back());
1692 buf += ": ;";
1693 buf += "\n\t\t";
1694 buf += "} while (counter < limit);\n\t";
1695 buf += "} while (limit = ";
1696 SynthCountByEnumWithState(buf);
1697 buf += ");\n\t";
1698 buf += elementName;
1699 buf += " = ((";
1700 buf += elementTypeAsString;
1701 buf += ")0);\n\t";
1702 buf += "__break_label_";
1703 buf += utostr(ObjCBcLabelNo.back());
1704 buf += ": ;\n\t";
1705 buf += "}\n\t";
1706 buf += "else\n\t\t";
1707 buf += elementName;
1708 buf += " = ((";
1709 buf += elementTypeAsString;
1710 buf += ")0);\n\t";
1711 buf += "}\n";
1712
1713 // Insert all these *after* the statement body.
1714 // FIXME: If this should support Obj-C++, support CXXTryStmt
1715 if (isa<CompoundStmt>(S->getBody())) {
1716 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1717 InsertText(endBodyLoc, buf);
1718 } else {
1719 /* Need to treat single statements specially. For example:
1720 *
1721 * for (A *a in b) if (stuff()) break;
1722 * for (A *a in b) xxxyy;
1723 *
1724 * The following code simply scans ahead to the semi to find the actual end.
1725 */
1726 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1727 const char *semiBuf = strchr(stmtBuf, ';');
1728 assert(semiBuf && "Can't find ';'");
1729 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1730 InsertText(endBodyLoc, buf);
1731 }
1732 Stmts.pop_back();
1733 ObjCBcLabelNo.pop_back();
1734 return 0;
1735}
1736
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001737static void Write_RethrowObject(std::string &buf) {
1738 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1739 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1740 buf += "\tid rethrow;\n";
1741 buf += "\t} _fin_force_rethow(_rethrow);";
1742}
1743
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001744/// RewriteObjCSynchronizedStmt -
1745/// This routine rewrites @synchronized(expr) stmt;
1746/// into:
1747/// objc_sync_enter(expr);
1748/// @try stmt @finally { objc_sync_exit(expr); }
1749///
1750Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1751 // Get the start location and compute the semi location.
1752 SourceLocation startLoc = S->getLocStart();
1753 const char *startBuf = SM->getCharacterData(startLoc);
1754
1755 assert((*startBuf == '@') && "bogus @synchronized location");
1756
1757 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001758 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001759
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001760 const char *lparenBuf = startBuf;
1761 while (*lparenBuf != '(') lparenBuf++;
1762 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001763
1764 buf = "; objc_sync_enter(_sync_obj);\n";
1765 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1766 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1767 buf += "\n\tid sync_exit;";
1768 buf += "\n\t} _sync_exit(_sync_obj);\n";
1769
1770 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1771 // the sync expression is typically a message expression that's already
1772 // been rewritten! (which implies the SourceLocation's are invalid).
1773 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1774 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1775 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1776 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1777
1778 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1779 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1780 assert (*LBraceLocBuf == '{');
1781 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001782
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001783 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001784 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1785 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001786
1787 buf = "} catch (id e) {_rethrow = e;}\n";
1788 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001789 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001790 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001791
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001792 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001793
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001794 return 0;
1795}
1796
1797void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1798{
1799 // Perform a bottom up traversal of all children.
1800 for (Stmt::child_range CI = S->children(); CI; ++CI)
1801 if (*CI)
1802 WarnAboutReturnGotoStmts(*CI);
1803
1804 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1805 Diags.Report(Context->getFullLoc(S->getLocStart()),
1806 TryFinallyContainsReturnDiag);
1807 }
1808 return;
1809}
1810
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001811Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001812 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001813 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001814 std::string buf;
1815
1816 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001817 if (noCatch)
1818 buf = "{ id volatile _rethrow = 0;\n";
1819 else {
1820 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1821 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001822 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001823 // Get the start location and compute the semi location.
1824 SourceLocation startLoc = S->getLocStart();
1825 const char *startBuf = SM->getCharacterData(startLoc);
1826
1827 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001828 if (finalStmt)
1829 ReplaceText(startLoc, 1, buf);
1830 else
1831 // @try -> try
1832 ReplaceText(startLoc, 1, "");
1833
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001834 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1835 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001836 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001837
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001838 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001839 bool AtRemoved = false;
1840 if (catchDecl) {
1841 QualType t = catchDecl->getType();
1842 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1843 // Should be a pointer to a class.
1844 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1845 if (IDecl) {
1846 std::string Result;
1847 startBuf = SM->getCharacterData(startLoc);
1848 assert((*startBuf == '@') && "bogus @catch location");
1849 SourceLocation rParenLoc = Catch->getRParenLoc();
1850 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1851
1852 // _objc_exc_Foo *_e as argument to catch.
1853 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1854 Result += " *_"; Result += catchDecl->getNameAsString();
1855 Result += ")";
1856 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1857 // Foo *e = (Foo *)_e;
1858 Result.clear();
1859 Result = "{ ";
1860 Result += IDecl->getNameAsString();
1861 Result += " *"; Result += catchDecl->getNameAsString();
1862 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1863 Result += "_"; Result += catchDecl->getNameAsString();
1864
1865 Result += "; ";
1866 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1867 ReplaceText(lBraceLoc, 1, Result);
1868 AtRemoved = true;
1869 }
1870 }
1871 }
1872 if (!AtRemoved)
1873 // @catch -> catch
1874 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001875
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001876 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001877 if (finalStmt) {
1878 buf.clear();
1879 if (noCatch)
1880 buf = "catch (id e) {_rethrow = e;}\n";
1881 else
1882 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1883
1884 SourceLocation startFinalLoc = finalStmt->getLocStart();
1885 ReplaceText(startFinalLoc, 8, buf);
1886 Stmt *body = finalStmt->getFinallyBody();
1887 SourceLocation startFinalBodyLoc = body->getLocStart();
1888 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001889 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001890 ReplaceText(startFinalBodyLoc, 1, buf);
1891
1892 SourceLocation endFinalBodyLoc = body->getLocEnd();
1893 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001894 // Now check for any return/continue/go statements within the @try.
1895 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001896 }
1897
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001898 return 0;
1899}
1900
1901// This can't be done with ReplaceStmt(S, ThrowExpr), since
1902// the throw expression is typically a message expression that's already
1903// been rewritten! (which implies the SourceLocation's are invalid).
1904Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1905 // Get the start location and compute the semi location.
1906 SourceLocation startLoc = S->getLocStart();
1907 const char *startBuf = SM->getCharacterData(startLoc);
1908
1909 assert((*startBuf == '@') && "bogus @throw location");
1910
1911 std::string buf;
1912 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1913 if (S->getThrowExpr())
1914 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001915 else
1916 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001917
1918 // handle "@ throw" correctly.
1919 const char *wBuf = strchr(startBuf, 'w');
1920 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1921 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1922
1923 const char *semiBuf = strchr(startBuf, ';');
1924 assert((*semiBuf == ';') && "@throw: can't find ';'");
1925 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001926 if (S->getThrowExpr())
1927 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001928 return 0;
1929}
1930
1931Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1932 // Create a new string expression.
1933 QualType StrType = Context->getPointerType(Context->CharTy);
1934 std::string StrEncoding;
1935 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1936 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1937 StringLiteral::Ascii, false,
1938 StrType, SourceLocation());
1939 ReplaceStmt(Exp, Replacement);
1940
1941 // Replace this subexpr in the parent.
1942 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1943 return Replacement;
1944}
1945
1946Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1947 if (!SelGetUidFunctionDecl)
1948 SynthSelGetUidFunctionDecl();
1949 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1950 // Create a call to sel_registerName("selName").
1951 SmallVector<Expr*, 8> SelExprs;
1952 QualType argType = Context->getPointerType(Context->CharTy);
1953 SelExprs.push_back(StringLiteral::Create(*Context,
1954 Exp->getSelector().getAsString(),
1955 StringLiteral::Ascii, false,
1956 argType, SourceLocation()));
1957 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1958 &SelExprs[0], SelExprs.size());
1959 ReplaceStmt(Exp, SelExp);
1960 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1961 return SelExp;
1962}
1963
1964CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1965 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1966 SourceLocation EndLoc) {
1967 // Get the type, we will need to reference it in a couple spots.
1968 QualType msgSendType = FD->getType();
1969
1970 // Create a reference to the objc_msgSend() declaration.
1971 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001972 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001973
1974 // Now, we cast the reference to a pointer to the objc_msgSend type.
1975 QualType pToFunc = Context->getPointerType(msgSendType);
1976 ImplicitCastExpr *ICE =
1977 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1978 DRE, 0, VK_RValue);
1979
1980 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1981
1982 CallExpr *Exp =
1983 new (Context) CallExpr(*Context, ICE, args, nargs,
1984 FT->getCallResultType(*Context),
1985 VK_RValue, EndLoc);
1986 return Exp;
1987}
1988
1989static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1990 const char *&startRef, const char *&endRef) {
1991 while (startBuf < endBuf) {
1992 if (*startBuf == '<')
1993 startRef = startBuf; // mark the start.
1994 if (*startBuf == '>') {
1995 if (startRef && *startRef == '<') {
1996 endRef = startBuf; // mark the end.
1997 return true;
1998 }
1999 return false;
2000 }
2001 startBuf++;
2002 }
2003 return false;
2004}
2005
2006static void scanToNextArgument(const char *&argRef) {
2007 int angle = 0;
2008 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2009 if (*argRef == '<')
2010 angle++;
2011 else if (*argRef == '>')
2012 angle--;
2013 argRef++;
2014 }
2015 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2016}
2017
2018bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2019 if (T->isObjCQualifiedIdType())
2020 return true;
2021 if (const PointerType *PT = T->getAs<PointerType>()) {
2022 if (PT->getPointeeType()->isObjCQualifiedIdType())
2023 return true;
2024 }
2025 if (T->isObjCObjectPointerType()) {
2026 T = T->getPointeeType();
2027 return T->isObjCQualifiedInterfaceType();
2028 }
2029 if (T->isArrayType()) {
2030 QualType ElemTy = Context->getBaseElementType(T);
2031 return needToScanForQualifiers(ElemTy);
2032 }
2033 return false;
2034}
2035
2036void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2037 QualType Type = E->getType();
2038 if (needToScanForQualifiers(Type)) {
2039 SourceLocation Loc, EndLoc;
2040
2041 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2042 Loc = ECE->getLParenLoc();
2043 EndLoc = ECE->getRParenLoc();
2044 } else {
2045 Loc = E->getLocStart();
2046 EndLoc = E->getLocEnd();
2047 }
2048 // This will defend against trying to rewrite synthesized expressions.
2049 if (Loc.isInvalid() || EndLoc.isInvalid())
2050 return;
2051
2052 const char *startBuf = SM->getCharacterData(Loc);
2053 const char *endBuf = SM->getCharacterData(EndLoc);
2054 const char *startRef = 0, *endRef = 0;
2055 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2056 // Get the locations of the startRef, endRef.
2057 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2058 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2059 // Comment out the protocol references.
2060 InsertText(LessLoc, "/*");
2061 InsertText(GreaterLoc, "*/");
2062 }
2063 }
2064}
2065
2066void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2067 SourceLocation Loc;
2068 QualType Type;
2069 const FunctionProtoType *proto = 0;
2070 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2071 Loc = VD->getLocation();
2072 Type = VD->getType();
2073 }
2074 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2075 Loc = FD->getLocation();
2076 // Check for ObjC 'id' and class types that have been adorned with protocol
2077 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2078 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2079 assert(funcType && "missing function type");
2080 proto = dyn_cast<FunctionProtoType>(funcType);
2081 if (!proto)
2082 return;
2083 Type = proto->getResultType();
2084 }
2085 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2086 Loc = FD->getLocation();
2087 Type = FD->getType();
2088 }
2089 else
2090 return;
2091
2092 if (needToScanForQualifiers(Type)) {
2093 // Since types are unique, we need to scan the buffer.
2094
2095 const char *endBuf = SM->getCharacterData(Loc);
2096 const char *startBuf = endBuf;
2097 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2098 startBuf--; // scan backward (from the decl location) for return type.
2099 const char *startRef = 0, *endRef = 0;
2100 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2101 // Get the locations of the startRef, endRef.
2102 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2103 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2104 // Comment out the protocol references.
2105 InsertText(LessLoc, "/*");
2106 InsertText(GreaterLoc, "*/");
2107 }
2108 }
2109 if (!proto)
2110 return; // most likely, was a variable
2111 // Now check arguments.
2112 const char *startBuf = SM->getCharacterData(Loc);
2113 const char *startFuncBuf = startBuf;
2114 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2115 if (needToScanForQualifiers(proto->getArgType(i))) {
2116 // Since types are unique, we need to scan the buffer.
2117
2118 const char *endBuf = startBuf;
2119 // scan forward (from the decl location) for argument types.
2120 scanToNextArgument(endBuf);
2121 const char *startRef = 0, *endRef = 0;
2122 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2123 // Get the locations of the startRef, endRef.
2124 SourceLocation LessLoc =
2125 Loc.getLocWithOffset(startRef-startFuncBuf);
2126 SourceLocation GreaterLoc =
2127 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2128 // Comment out the protocol references.
2129 InsertText(LessLoc, "/*");
2130 InsertText(GreaterLoc, "*/");
2131 }
2132 startBuf = ++endBuf;
2133 }
2134 else {
2135 // If the function name is derived from a macro expansion, then the
2136 // argument buffer will not follow the name. Need to speak with Chris.
2137 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2138 startBuf++; // scan forward (from the decl location) for argument types.
2139 startBuf++;
2140 }
2141 }
2142}
2143
2144void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2145 QualType QT = ND->getType();
2146 const Type* TypePtr = QT->getAs<Type>();
2147 if (!isa<TypeOfExprType>(TypePtr))
2148 return;
2149 while (isa<TypeOfExprType>(TypePtr)) {
2150 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2151 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2152 TypePtr = QT->getAs<Type>();
2153 }
2154 // FIXME. This will not work for multiple declarators; as in:
2155 // __typeof__(a) b,c,d;
2156 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2157 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2158 const char *startBuf = SM->getCharacterData(DeclLoc);
2159 if (ND->getInit()) {
2160 std::string Name(ND->getNameAsString());
2161 TypeAsString += " " + Name + " = ";
2162 Expr *E = ND->getInit();
2163 SourceLocation startLoc;
2164 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2165 startLoc = ECE->getLParenLoc();
2166 else
2167 startLoc = E->getLocStart();
2168 startLoc = SM->getExpansionLoc(startLoc);
2169 const char *endBuf = SM->getCharacterData(startLoc);
2170 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2171 }
2172 else {
2173 SourceLocation X = ND->getLocEnd();
2174 X = SM->getExpansionLoc(X);
2175 const char *endBuf = SM->getCharacterData(X);
2176 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2177 }
2178}
2179
2180// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2181void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2182 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2183 SmallVector<QualType, 16> ArgTys;
2184 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2185 QualType getFuncType =
2186 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2187 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2188 SourceLocation(),
2189 SourceLocation(),
2190 SelGetUidIdent, getFuncType, 0,
2191 SC_Extern,
2192 SC_None, false);
2193}
2194
2195void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2196 // declared in <objc/objc.h>
2197 if (FD->getIdentifier() &&
2198 FD->getName() == "sel_registerName") {
2199 SelGetUidFunctionDecl = FD;
2200 return;
2201 }
2202 RewriteObjCQualifiedInterfaceTypes(FD);
2203}
2204
2205void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2206 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2207 const char *argPtr = TypeString.c_str();
2208 if (!strchr(argPtr, '^')) {
2209 Str += TypeString;
2210 return;
2211 }
2212 while (*argPtr) {
2213 Str += (*argPtr == '^' ? '*' : *argPtr);
2214 argPtr++;
2215 }
2216}
2217
2218// FIXME. Consolidate this routine with RewriteBlockPointerType.
2219void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2220 ValueDecl *VD) {
2221 QualType Type = VD->getType();
2222 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2223 const char *argPtr = TypeString.c_str();
2224 int paren = 0;
2225 while (*argPtr) {
2226 switch (*argPtr) {
2227 case '(':
2228 Str += *argPtr;
2229 paren++;
2230 break;
2231 case ')':
2232 Str += *argPtr;
2233 paren--;
2234 break;
2235 case '^':
2236 Str += '*';
2237 if (paren == 1)
2238 Str += VD->getNameAsString();
2239 break;
2240 default:
2241 Str += *argPtr;
2242 break;
2243 }
2244 argPtr++;
2245 }
2246}
2247
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002248// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002249void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2250 if (SuperContructorFunctionDecl)
2251 return;
2252 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2253 SmallVector<QualType, 16> ArgTys;
2254 QualType argT = Context->getObjCIdType();
2255 assert(!argT.isNull() && "Can't find 'id' type");
2256 ArgTys.push_back(argT);
2257 ArgTys.push_back(argT);
2258 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2259 &ArgTys[0], ArgTys.size());
2260 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2261 SourceLocation(),
2262 SourceLocation(),
2263 msgSendIdent, msgSendType, 0,
2264 SC_Extern,
2265 SC_None, false);
2266}
2267
2268// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2269void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2270 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2271 SmallVector<QualType, 16> ArgTys;
2272 QualType argT = Context->getObjCIdType();
2273 assert(!argT.isNull() && "Can't find 'id' type");
2274 ArgTys.push_back(argT);
2275 argT = Context->getObjCSelType();
2276 assert(!argT.isNull() && "Can't find 'SEL' type");
2277 ArgTys.push_back(argT);
2278 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2279 &ArgTys[0], ArgTys.size(),
2280 true /*isVariadic*/);
2281 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2282 SourceLocation(),
2283 SourceLocation(),
2284 msgSendIdent, msgSendType, 0,
2285 SC_Extern,
2286 SC_None, false);
2287}
2288
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002289// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002290void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2291 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002292 SmallVector<QualType, 2> ArgTys;
2293 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002294 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002295 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002296 true /*isVariadic*/);
2297 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2298 SourceLocation(),
2299 SourceLocation(),
2300 msgSendIdent, msgSendType, 0,
2301 SC_Extern,
2302 SC_None, false);
2303}
2304
2305// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2306void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2307 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2308 SmallVector<QualType, 16> ArgTys;
2309 QualType argT = Context->getObjCIdType();
2310 assert(!argT.isNull() && "Can't find 'id' type");
2311 ArgTys.push_back(argT);
2312 argT = Context->getObjCSelType();
2313 assert(!argT.isNull() && "Can't find 'SEL' type");
2314 ArgTys.push_back(argT);
2315 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2316 &ArgTys[0], ArgTys.size(),
2317 true /*isVariadic*/);
2318 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319 SourceLocation(),
2320 SourceLocation(),
2321 msgSendIdent, msgSendType, 0,
2322 SC_Extern,
2323 SC_None, false);
2324}
2325
2326// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002327// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002328void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2329 IdentifierInfo *msgSendIdent =
2330 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002331 SmallVector<QualType, 2> ArgTys;
2332 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002333 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002334 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002335 true /*isVariadic*/);
2336 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2337 SourceLocation(),
2338 SourceLocation(),
2339 msgSendIdent, msgSendType, 0,
2340 SC_Extern,
2341 SC_None, false);
2342}
2343
2344// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2345void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2346 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2347 SmallVector<QualType, 16> ArgTys;
2348 QualType argT = Context->getObjCIdType();
2349 assert(!argT.isNull() && "Can't find 'id' type");
2350 ArgTys.push_back(argT);
2351 argT = Context->getObjCSelType();
2352 assert(!argT.isNull() && "Can't find 'SEL' type");
2353 ArgTys.push_back(argT);
2354 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2355 &ArgTys[0], ArgTys.size(),
2356 true /*isVariadic*/);
2357 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2358 SourceLocation(),
2359 SourceLocation(),
2360 msgSendIdent, msgSendType, 0,
2361 SC_Extern,
2362 SC_None, false);
2363}
2364
2365// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2366void RewriteModernObjC::SynthGetClassFunctionDecl() {
2367 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2368 SmallVector<QualType, 16> ArgTys;
2369 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2370 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2371 &ArgTys[0], ArgTys.size());
2372 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2373 SourceLocation(),
2374 SourceLocation(),
2375 getClassIdent, getClassType, 0,
2376 SC_Extern,
2377 SC_None, false);
2378}
2379
2380// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2381void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2382 IdentifierInfo *getSuperClassIdent =
2383 &Context->Idents.get("class_getSuperclass");
2384 SmallVector<QualType, 16> ArgTys;
2385 ArgTys.push_back(Context->getObjCClassType());
2386 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2387 &ArgTys[0], ArgTys.size());
2388 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2389 SourceLocation(),
2390 SourceLocation(),
2391 getSuperClassIdent,
2392 getClassType, 0,
2393 SC_Extern,
2394 SC_None,
2395 false);
2396}
2397
2398// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2399void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2400 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2401 SmallVector<QualType, 16> ArgTys;
2402 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2403 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2404 &ArgTys[0], ArgTys.size());
2405 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2406 SourceLocation(),
2407 SourceLocation(),
2408 getClassIdent, getClassType, 0,
2409 SC_Extern,
2410 SC_None, false);
2411}
2412
2413Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2414 QualType strType = getConstantStringStructType();
2415
2416 std::string S = "__NSConstantStringImpl_";
2417
2418 std::string tmpName = InFileName;
2419 unsigned i;
2420 for (i=0; i < tmpName.length(); i++) {
2421 char c = tmpName.at(i);
2422 // replace any non alphanumeric characters with '_'.
2423 if (!isalpha(c) && (c < '0' || c > '9'))
2424 tmpName[i] = '_';
2425 }
2426 S += tmpName;
2427 S += "_";
2428 S += utostr(NumObjCStringLiterals++);
2429
2430 Preamble += "static __NSConstantStringImpl " + S;
2431 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2432 Preamble += "0x000007c8,"; // utf8_str
2433 // The pretty printer for StringLiteral handles escape characters properly.
2434 std::string prettyBufS;
2435 llvm::raw_string_ostream prettyBuf(prettyBufS);
2436 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2437 PrintingPolicy(LangOpts));
2438 Preamble += prettyBuf.str();
2439 Preamble += ",";
2440 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2441
2442 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2443 SourceLocation(), &Context->Idents.get(S),
2444 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002445 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002446 SourceLocation());
2447 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2448 Context->getPointerType(DRE->getType()),
2449 VK_RValue, OK_Ordinary,
2450 SourceLocation());
2451 // cast to NSConstantString *
2452 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2453 CK_CPointerToObjCPointerCast, Unop);
2454 ReplaceStmt(Exp, cast);
2455 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2456 return cast;
2457}
2458
Fariborz Jahanian55947042012-03-27 20:17:30 +00002459Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2460 unsigned IntSize =
2461 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2462
2463 Expr *FlagExp = IntegerLiteral::Create(*Context,
2464 llvm::APInt(IntSize, Exp->getValue()),
2465 Context->IntTy, Exp->getLocation());
2466 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2467 CK_BitCast, FlagExp);
2468 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2469 cast);
2470 ReplaceStmt(Exp, PE);
2471 return PE;
2472}
2473
Patrick Beardeb382ec2012-04-19 00:25:12 +00002474Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002475 // synthesize declaration of helper functions needed in this routine.
2476 if (!SelGetUidFunctionDecl)
2477 SynthSelGetUidFunctionDecl();
2478 // use objc_msgSend() for all.
2479 if (!MsgSendFunctionDecl)
2480 SynthMsgSendFunctionDecl();
2481 if (!GetClassFunctionDecl)
2482 SynthGetClassFunctionDecl();
2483
2484 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2485 SourceLocation StartLoc = Exp->getLocStart();
2486 SourceLocation EndLoc = Exp->getLocEnd();
2487
2488 // Synthesize a call to objc_msgSend().
2489 SmallVector<Expr*, 4> MsgExprs;
2490 SmallVector<Expr*, 4> ClsExprs;
2491 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002492
Patrick Beardeb382ec2012-04-19 00:25:12 +00002493 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2494 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2495 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002496
Patrick Beardeb382ec2012-04-19 00:25:12 +00002497 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002498 ClsExprs.push_back(StringLiteral::Create(*Context,
2499 clsName->getName(),
2500 StringLiteral::Ascii, false,
2501 argType, SourceLocation()));
2502 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2503 &ClsExprs[0],
2504 ClsExprs.size(),
2505 StartLoc, EndLoc);
2506 MsgExprs.push_back(Cls);
2507
Patrick Beardeb382ec2012-04-19 00:25:12 +00002508 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002509 // it will be the 2nd argument.
2510 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002511 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002512 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002513 StringLiteral::Ascii, false,
2514 argType, SourceLocation()));
2515 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2516 &SelExprs[0], SelExprs.size(),
2517 StartLoc, EndLoc);
2518 MsgExprs.push_back(SelExp);
2519
Patrick Beardeb382ec2012-04-19 00:25:12 +00002520 // User provided sub-expression is the 3rd, and last, argument.
2521 Expr *subExpr = Exp->getSubExpr();
2522 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002523 QualType type = ICE->getType();
2524 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2525 CastKind CK = CK_BitCast;
2526 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2527 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002528 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002529 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002530 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002531
2532 SmallVector<QualType, 4> ArgTypes;
2533 ArgTypes.push_back(Context->getObjCIdType());
2534 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002535 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2536 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002537 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002538
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002539 QualType returnType = Exp->getType();
2540 // Get the type, we will need to reference it in a couple spots.
2541 QualType msgSendType = MsgSendFlavor->getType();
2542
2543 // Create a reference to the objc_msgSend() declaration.
2544 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2545 VK_LValue, SourceLocation());
2546
2547 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002548 Context->getPointerType(Context->VoidTy),
2549 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002550
2551 // Now do the "normal" pointer to function cast.
2552 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002553 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2554 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002555 castType = Context->getPointerType(castType);
2556 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2557 cast);
2558
2559 // Don't forget the parens to enforce the proper binding.
2560 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2561
2562 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2563 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2564 MsgExprs.size(),
2565 FT->getResultType(), VK_RValue,
2566 EndLoc);
2567 ReplaceStmt(Exp, CE);
2568 return CE;
2569}
2570
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002571Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2572 // synthesize declaration of helper functions needed in this routine.
2573 if (!SelGetUidFunctionDecl)
2574 SynthSelGetUidFunctionDecl();
2575 // use objc_msgSend() for all.
2576 if (!MsgSendFunctionDecl)
2577 SynthMsgSendFunctionDecl();
2578 if (!GetClassFunctionDecl)
2579 SynthGetClassFunctionDecl();
2580
2581 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2582 SourceLocation StartLoc = Exp->getLocStart();
2583 SourceLocation EndLoc = Exp->getLocEnd();
2584
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002585 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002586 QualType IntQT = Context->IntTy;
2587 QualType NSArrayFType =
2588 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002589 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002590 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2591 DeclRefExpr *NSArrayDRE =
2592 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2593 SourceLocation());
2594
2595 SmallVector<Expr*, 16> InitExprs;
2596 unsigned NumElements = Exp->getNumElements();
2597 unsigned UnsignedIntSize =
2598 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2599 Expr *count = IntegerLiteral::Create(*Context,
2600 llvm::APInt(UnsignedIntSize, NumElements),
2601 Context->UnsignedIntTy, SourceLocation());
2602 InitExprs.push_back(count);
2603 for (unsigned i = 0; i < NumElements; i++)
2604 InitExprs.push_back(Exp->getElement(i));
2605 Expr *NSArrayCallExpr =
2606 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2607 NSArrayFType, VK_LValue, SourceLocation());
2608
2609 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2610 SourceLocation(),
2611 &Context->Idents.get("arr"),
2612 Context->getPointerType(Context->VoidPtrTy), 0,
2613 /*BitWidth=*/0, /*Mutable=*/true,
2614 /*HasInit=*/false);
2615 MemberExpr *ArrayLiteralME =
2616 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2617 SourceLocation(),
2618 ARRFD->getType(), VK_LValue,
2619 OK_Ordinary);
2620 QualType ConstIdT = Context->getObjCIdType().withConst();
2621 CStyleCastExpr * ArrayLiteralObjects =
2622 NoTypeInfoCStyleCastExpr(Context,
2623 Context->getPointerType(ConstIdT),
2624 CK_BitCast,
2625 ArrayLiteralME);
2626
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002627 // Synthesize a call to objc_msgSend().
2628 SmallVector<Expr*, 32> MsgExprs;
2629 SmallVector<Expr*, 4> ClsExprs;
2630 QualType argType = Context->getPointerType(Context->CharTy);
2631 QualType expType = Exp->getType();
2632
2633 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2634 ObjCInterfaceDecl *Class =
2635 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2636
2637 IdentifierInfo *clsName = Class->getIdentifier();
2638 ClsExprs.push_back(StringLiteral::Create(*Context,
2639 clsName->getName(),
2640 StringLiteral::Ascii, false,
2641 argType, SourceLocation()));
2642 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2643 &ClsExprs[0],
2644 ClsExprs.size(),
2645 StartLoc, EndLoc);
2646 MsgExprs.push_back(Cls);
2647
2648 // Create a call to sel_registerName("arrayWithObjects:count:").
2649 // it will be the 2nd argument.
2650 SmallVector<Expr*, 4> SelExprs;
2651 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2652 SelExprs.push_back(StringLiteral::Create(*Context,
2653 ArrayMethod->getSelector().getAsString(),
2654 StringLiteral::Ascii, false,
2655 argType, SourceLocation()));
2656 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2657 &SelExprs[0], SelExprs.size(),
2658 StartLoc, EndLoc);
2659 MsgExprs.push_back(SelExp);
2660
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002661 // (const id [])objects
2662 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002663
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002664 // (NSUInteger)cnt
2665 Expr *cnt = IntegerLiteral::Create(*Context,
2666 llvm::APInt(UnsignedIntSize, NumElements),
2667 Context->UnsignedIntTy, SourceLocation());
2668 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002669
2670
2671 SmallVector<QualType, 4> ArgTypes;
2672 ArgTypes.push_back(Context->getObjCIdType());
2673 ArgTypes.push_back(Context->getObjCSelType());
2674 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2675 E = ArrayMethod->param_end(); PI != E; ++PI)
2676 ArgTypes.push_back((*PI)->getType());
2677
2678 QualType returnType = Exp->getType();
2679 // Get the type, we will need to reference it in a couple spots.
2680 QualType msgSendType = MsgSendFlavor->getType();
2681
2682 // Create a reference to the objc_msgSend() declaration.
2683 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2684 VK_LValue, SourceLocation());
2685
2686 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2687 Context->getPointerType(Context->VoidTy),
2688 CK_BitCast, DRE);
2689
2690 // Now do the "normal" pointer to function cast.
2691 QualType castType =
2692 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2693 ArrayMethod->isVariadic());
2694 castType = Context->getPointerType(castType);
2695 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2696 cast);
2697
2698 // Don't forget the parens to enforce the proper binding.
2699 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2700
2701 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2702 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2703 MsgExprs.size(),
2704 FT->getResultType(), VK_RValue,
2705 EndLoc);
2706 ReplaceStmt(Exp, CE);
2707 return CE;
2708}
2709
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002710Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2711 // synthesize declaration of helper functions needed in this routine.
2712 if (!SelGetUidFunctionDecl)
2713 SynthSelGetUidFunctionDecl();
2714 // use objc_msgSend() for all.
2715 if (!MsgSendFunctionDecl)
2716 SynthMsgSendFunctionDecl();
2717 if (!GetClassFunctionDecl)
2718 SynthGetClassFunctionDecl();
2719
2720 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2721 SourceLocation StartLoc = Exp->getLocStart();
2722 SourceLocation EndLoc = Exp->getLocEnd();
2723
2724 // Build the expression: __NSContainer_literal(int, ...).arr
2725 QualType IntQT = Context->IntTy;
2726 QualType NSDictFType =
2727 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2728 std::string NSDictFName("__NSContainer_literal");
2729 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2730 DeclRefExpr *NSDictDRE =
2731 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2732 SourceLocation());
2733
2734 SmallVector<Expr*, 16> KeyExprs;
2735 SmallVector<Expr*, 16> ValueExprs;
2736
2737 unsigned NumElements = Exp->getNumElements();
2738 unsigned UnsignedIntSize =
2739 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2740 Expr *count = IntegerLiteral::Create(*Context,
2741 llvm::APInt(UnsignedIntSize, NumElements),
2742 Context->UnsignedIntTy, SourceLocation());
2743 KeyExprs.push_back(count);
2744 ValueExprs.push_back(count);
2745 for (unsigned i = 0; i < NumElements; i++) {
2746 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2747 KeyExprs.push_back(Element.Key);
2748 ValueExprs.push_back(Element.Value);
2749 }
2750
2751 // (const id [])objects
2752 Expr *NSValueCallExpr =
2753 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2754 NSDictFType, VK_LValue, SourceLocation());
2755
2756 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2757 SourceLocation(),
2758 &Context->Idents.get("arr"),
2759 Context->getPointerType(Context->VoidPtrTy), 0,
2760 /*BitWidth=*/0, /*Mutable=*/true,
2761 /*HasInit=*/false);
2762 MemberExpr *DictLiteralValueME =
2763 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2764 SourceLocation(),
2765 ARRFD->getType(), VK_LValue,
2766 OK_Ordinary);
2767 QualType ConstIdT = Context->getObjCIdType().withConst();
2768 CStyleCastExpr * DictValueObjects =
2769 NoTypeInfoCStyleCastExpr(Context,
2770 Context->getPointerType(ConstIdT),
2771 CK_BitCast,
2772 DictLiteralValueME);
2773 // (const id <NSCopying> [])keys
2774 Expr *NSKeyCallExpr =
2775 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2776 NSDictFType, VK_LValue, SourceLocation());
2777
2778 MemberExpr *DictLiteralKeyME =
2779 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2780 SourceLocation(),
2781 ARRFD->getType(), VK_LValue,
2782 OK_Ordinary);
2783
2784 CStyleCastExpr * DictKeyObjects =
2785 NoTypeInfoCStyleCastExpr(Context,
2786 Context->getPointerType(ConstIdT),
2787 CK_BitCast,
2788 DictLiteralKeyME);
2789
2790
2791
2792 // Synthesize a call to objc_msgSend().
2793 SmallVector<Expr*, 32> MsgExprs;
2794 SmallVector<Expr*, 4> ClsExprs;
2795 QualType argType = Context->getPointerType(Context->CharTy);
2796 QualType expType = Exp->getType();
2797
2798 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2799 ObjCInterfaceDecl *Class =
2800 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2801
2802 IdentifierInfo *clsName = Class->getIdentifier();
2803 ClsExprs.push_back(StringLiteral::Create(*Context,
2804 clsName->getName(),
2805 StringLiteral::Ascii, false,
2806 argType, SourceLocation()));
2807 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2808 &ClsExprs[0],
2809 ClsExprs.size(),
2810 StartLoc, EndLoc);
2811 MsgExprs.push_back(Cls);
2812
2813 // Create a call to sel_registerName("arrayWithObjects:count:").
2814 // it will be the 2nd argument.
2815 SmallVector<Expr*, 4> SelExprs;
2816 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2817 SelExprs.push_back(StringLiteral::Create(*Context,
2818 DictMethod->getSelector().getAsString(),
2819 StringLiteral::Ascii, false,
2820 argType, SourceLocation()));
2821 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2822 &SelExprs[0], SelExprs.size(),
2823 StartLoc, EndLoc);
2824 MsgExprs.push_back(SelExp);
2825
2826 // (const id [])objects
2827 MsgExprs.push_back(DictValueObjects);
2828
2829 // (const id <NSCopying> [])keys
2830 MsgExprs.push_back(DictKeyObjects);
2831
2832 // (NSUInteger)cnt
2833 Expr *cnt = IntegerLiteral::Create(*Context,
2834 llvm::APInt(UnsignedIntSize, NumElements),
2835 Context->UnsignedIntTy, SourceLocation());
2836 MsgExprs.push_back(cnt);
2837
2838
2839 SmallVector<QualType, 8> ArgTypes;
2840 ArgTypes.push_back(Context->getObjCIdType());
2841 ArgTypes.push_back(Context->getObjCSelType());
2842 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2843 E = DictMethod->param_end(); PI != E; ++PI) {
2844 QualType T = (*PI)->getType();
2845 if (const PointerType* PT = T->getAs<PointerType>()) {
2846 QualType PointeeTy = PT->getPointeeType();
2847 convertToUnqualifiedObjCType(PointeeTy);
2848 T = Context->getPointerType(PointeeTy);
2849 }
2850 ArgTypes.push_back(T);
2851 }
2852
2853 QualType returnType = Exp->getType();
2854 // Get the type, we will need to reference it in a couple spots.
2855 QualType msgSendType = MsgSendFlavor->getType();
2856
2857 // Create a reference to the objc_msgSend() declaration.
2858 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2859 VK_LValue, SourceLocation());
2860
2861 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2862 Context->getPointerType(Context->VoidTy),
2863 CK_BitCast, DRE);
2864
2865 // Now do the "normal" pointer to function cast.
2866 QualType castType =
2867 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2868 DictMethod->isVariadic());
2869 castType = Context->getPointerType(castType);
2870 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2871 cast);
2872
2873 // Don't forget the parens to enforce the proper binding.
2874 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2875
2876 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2877 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2878 MsgExprs.size(),
2879 FT->getResultType(), VK_RValue,
2880 EndLoc);
2881 ReplaceStmt(Exp, CE);
2882 return CE;
2883}
2884
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002885// struct __rw_objc_super {
2886// struct objc_object *object; struct objc_object *superClass;
2887// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002888QualType RewriteModernObjC::getSuperStructType() {
2889 if (!SuperStructDecl) {
2890 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2891 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002892 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002893 QualType FieldTypes[2];
2894
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002895 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002896 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002897 // struct objc_object *superClass;
2898 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002899
2900 // Create fields
2901 for (unsigned i = 0; i < 2; ++i) {
2902 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2903 SourceLocation(),
2904 SourceLocation(), 0,
2905 FieldTypes[i], 0,
2906 /*BitWidth=*/0,
2907 /*Mutable=*/false,
2908 /*HasInit=*/false));
2909 }
2910
2911 SuperStructDecl->completeDefinition();
2912 }
2913 return Context->getTagDeclType(SuperStructDecl);
2914}
2915
2916QualType RewriteModernObjC::getConstantStringStructType() {
2917 if (!ConstantStringDecl) {
2918 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2919 SourceLocation(), SourceLocation(),
2920 &Context->Idents.get("__NSConstantStringImpl"));
2921 QualType FieldTypes[4];
2922
2923 // struct objc_object *receiver;
2924 FieldTypes[0] = Context->getObjCIdType();
2925 // int flags;
2926 FieldTypes[1] = Context->IntTy;
2927 // char *str;
2928 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2929 // long length;
2930 FieldTypes[3] = Context->LongTy;
2931
2932 // Create fields
2933 for (unsigned i = 0; i < 4; ++i) {
2934 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2935 ConstantStringDecl,
2936 SourceLocation(),
2937 SourceLocation(), 0,
2938 FieldTypes[i], 0,
2939 /*BitWidth=*/0,
2940 /*Mutable=*/true,
2941 /*HasInit=*/false));
2942 }
2943
2944 ConstantStringDecl->completeDefinition();
2945 }
2946 return Context->getTagDeclType(ConstantStringDecl);
2947}
2948
2949Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2950 SourceLocation StartLoc,
2951 SourceLocation EndLoc) {
2952 if (!SelGetUidFunctionDecl)
2953 SynthSelGetUidFunctionDecl();
2954 if (!MsgSendFunctionDecl)
2955 SynthMsgSendFunctionDecl();
2956 if (!MsgSendSuperFunctionDecl)
2957 SynthMsgSendSuperFunctionDecl();
2958 if (!MsgSendStretFunctionDecl)
2959 SynthMsgSendStretFunctionDecl();
2960 if (!MsgSendSuperStretFunctionDecl)
2961 SynthMsgSendSuperStretFunctionDecl();
2962 if (!MsgSendFpretFunctionDecl)
2963 SynthMsgSendFpretFunctionDecl();
2964 if (!GetClassFunctionDecl)
2965 SynthGetClassFunctionDecl();
2966 if (!GetSuperClassFunctionDecl)
2967 SynthGetSuperClassFunctionDecl();
2968 if (!GetMetaClassFunctionDecl)
2969 SynthGetMetaClassFunctionDecl();
2970
2971 // default to objc_msgSend().
2972 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2973 // May need to use objc_msgSend_stret() as well.
2974 FunctionDecl *MsgSendStretFlavor = 0;
2975 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2976 QualType resultType = mDecl->getResultType();
2977 if (resultType->isRecordType())
2978 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2979 else if (resultType->isRealFloatingType())
2980 MsgSendFlavor = MsgSendFpretFunctionDecl;
2981 }
2982
2983 // Synthesize a call to objc_msgSend().
2984 SmallVector<Expr*, 8> MsgExprs;
2985 switch (Exp->getReceiverKind()) {
2986 case ObjCMessageExpr::SuperClass: {
2987 MsgSendFlavor = MsgSendSuperFunctionDecl;
2988 if (MsgSendStretFlavor)
2989 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2990 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2991
2992 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2993
2994 SmallVector<Expr*, 4> InitExprs;
2995
2996 // set the receiver to self, the first argument to all methods.
2997 InitExprs.push_back(
2998 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2999 CK_BitCast,
3000 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003001 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003002 Context->getObjCIdType(),
3003 VK_RValue,
3004 SourceLocation()))
3005 ); // set the 'receiver'.
3006
3007 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3008 SmallVector<Expr*, 8> ClsExprs;
3009 QualType argType = Context->getPointerType(Context->CharTy);
3010 ClsExprs.push_back(StringLiteral::Create(*Context,
3011 ClassDecl->getIdentifier()->getName(),
3012 StringLiteral::Ascii, false,
3013 argType, SourceLocation()));
3014 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3015 &ClsExprs[0],
3016 ClsExprs.size(),
3017 StartLoc,
3018 EndLoc);
3019 // (Class)objc_getClass("CurrentClass")
3020 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3021 Context->getObjCClassType(),
3022 CK_BitCast, Cls);
3023 ClsExprs.clear();
3024 ClsExprs.push_back(ArgExpr);
3025 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3026 &ClsExprs[0], ClsExprs.size(),
3027 StartLoc, EndLoc);
3028
3029 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3030 // To turn off a warning, type-cast to 'id'
3031 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3032 NoTypeInfoCStyleCastExpr(Context,
3033 Context->getObjCIdType(),
3034 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003035 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003036 QualType superType = getSuperStructType();
3037 Expr *SuperRep;
3038
3039 if (LangOpts.MicrosoftExt) {
3040 SynthSuperContructorFunctionDecl();
3041 // Simulate a contructor call...
3042 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003043 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003044 SourceLocation());
3045 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3046 InitExprs.size(),
3047 superType, VK_LValue,
3048 SourceLocation());
3049 // The code for super is a little tricky to prevent collision with
3050 // the structure definition in the header. The rewriter has it's own
3051 // internal definition (__rw_objc_super) that is uses. This is why
3052 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003053 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003054 //
3055 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3056 Context->getPointerType(SuperRep->getType()),
3057 VK_RValue, OK_Ordinary,
3058 SourceLocation());
3059 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3060 Context->getPointerType(superType),
3061 CK_BitCast, SuperRep);
3062 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003063 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003064 InitListExpr *ILE =
3065 new (Context) InitListExpr(*Context, SourceLocation(),
3066 &InitExprs[0], InitExprs.size(),
3067 SourceLocation());
3068 TypeSourceInfo *superTInfo
3069 = Context->getTrivialTypeSourceInfo(superType);
3070 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3071 superType, VK_LValue,
3072 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003073 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003074 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3075 Context->getPointerType(SuperRep->getType()),
3076 VK_RValue, OK_Ordinary,
3077 SourceLocation());
3078 }
3079 MsgExprs.push_back(SuperRep);
3080 break;
3081 }
3082
3083 case ObjCMessageExpr::Class: {
3084 SmallVector<Expr*, 8> ClsExprs;
3085 QualType argType = Context->getPointerType(Context->CharTy);
3086 ObjCInterfaceDecl *Class
3087 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3088 IdentifierInfo *clsName = Class->getIdentifier();
3089 ClsExprs.push_back(StringLiteral::Create(*Context,
3090 clsName->getName(),
3091 StringLiteral::Ascii, false,
3092 argType, SourceLocation()));
3093 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3094 &ClsExprs[0],
3095 ClsExprs.size(),
3096 StartLoc, EndLoc);
3097 MsgExprs.push_back(Cls);
3098 break;
3099 }
3100
3101 case ObjCMessageExpr::SuperInstance:{
3102 MsgSendFlavor = MsgSendSuperFunctionDecl;
3103 if (MsgSendStretFlavor)
3104 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3105 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3106 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3107 SmallVector<Expr*, 4> InitExprs;
3108
3109 InitExprs.push_back(
3110 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3111 CK_BitCast,
3112 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003113 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003114 Context->getObjCIdType(),
3115 VK_RValue, SourceLocation()))
3116 ); // set the 'receiver'.
3117
3118 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3119 SmallVector<Expr*, 8> ClsExprs;
3120 QualType argType = Context->getPointerType(Context->CharTy);
3121 ClsExprs.push_back(StringLiteral::Create(*Context,
3122 ClassDecl->getIdentifier()->getName(),
3123 StringLiteral::Ascii, false, argType,
3124 SourceLocation()));
3125 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3126 &ClsExprs[0],
3127 ClsExprs.size(),
3128 StartLoc, EndLoc);
3129 // (Class)objc_getClass("CurrentClass")
3130 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3131 Context->getObjCClassType(),
3132 CK_BitCast, Cls);
3133 ClsExprs.clear();
3134 ClsExprs.push_back(ArgExpr);
3135 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3136 &ClsExprs[0], ClsExprs.size(),
3137 StartLoc, EndLoc);
3138
3139 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3140 // To turn off a warning, type-cast to 'id'
3141 InitExprs.push_back(
3142 // set 'super class', using class_getSuperclass().
3143 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3144 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003145 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003146 QualType superType = getSuperStructType();
3147 Expr *SuperRep;
3148
3149 if (LangOpts.MicrosoftExt) {
3150 SynthSuperContructorFunctionDecl();
3151 // Simulate a contructor call...
3152 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003153 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003154 SourceLocation());
3155 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3156 InitExprs.size(),
3157 superType, VK_LValue, SourceLocation());
3158 // The code for super is a little tricky to prevent collision with
3159 // the structure definition in the header. The rewriter has it's own
3160 // internal definition (__rw_objc_super) that is uses. This is why
3161 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003162 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003163 //
3164 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3165 Context->getPointerType(SuperRep->getType()),
3166 VK_RValue, OK_Ordinary,
3167 SourceLocation());
3168 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3169 Context->getPointerType(superType),
3170 CK_BitCast, SuperRep);
3171 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003172 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003173 InitListExpr *ILE =
3174 new (Context) InitListExpr(*Context, SourceLocation(),
3175 &InitExprs[0], InitExprs.size(),
3176 SourceLocation());
3177 TypeSourceInfo *superTInfo
3178 = Context->getTrivialTypeSourceInfo(superType);
3179 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3180 superType, VK_RValue, ILE,
3181 false);
3182 }
3183 MsgExprs.push_back(SuperRep);
3184 break;
3185 }
3186
3187 case ObjCMessageExpr::Instance: {
3188 // Remove all type-casts because it may contain objc-style types; e.g.
3189 // Foo<Proto> *.
3190 Expr *recExpr = Exp->getInstanceReceiver();
3191 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3192 recExpr = CE->getSubExpr();
3193 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3194 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3195 ? CK_BlockPointerToObjCPointerCast
3196 : CK_CPointerToObjCPointerCast;
3197
3198 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3199 CK, recExpr);
3200 MsgExprs.push_back(recExpr);
3201 break;
3202 }
3203 }
3204
3205 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3206 SmallVector<Expr*, 8> SelExprs;
3207 QualType argType = Context->getPointerType(Context->CharTy);
3208 SelExprs.push_back(StringLiteral::Create(*Context,
3209 Exp->getSelector().getAsString(),
3210 StringLiteral::Ascii, false,
3211 argType, SourceLocation()));
3212 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3213 &SelExprs[0], SelExprs.size(),
3214 StartLoc,
3215 EndLoc);
3216 MsgExprs.push_back(SelExp);
3217
3218 // Now push any user supplied arguments.
3219 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3220 Expr *userExpr = Exp->getArg(i);
3221 // Make all implicit casts explicit...ICE comes in handy:-)
3222 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3223 // Reuse the ICE type, it is exactly what the doctor ordered.
3224 QualType type = ICE->getType();
3225 if (needToScanForQualifiers(type))
3226 type = Context->getObjCIdType();
3227 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3228 (void)convertBlockPointerToFunctionPointer(type);
3229 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3230 CastKind CK;
3231 if (SubExpr->getType()->isIntegralType(*Context) &&
3232 type->isBooleanType()) {
3233 CK = CK_IntegralToBoolean;
3234 } else if (type->isObjCObjectPointerType()) {
3235 if (SubExpr->getType()->isBlockPointerType()) {
3236 CK = CK_BlockPointerToObjCPointerCast;
3237 } else if (SubExpr->getType()->isPointerType()) {
3238 CK = CK_CPointerToObjCPointerCast;
3239 } else {
3240 CK = CK_BitCast;
3241 }
3242 } else {
3243 CK = CK_BitCast;
3244 }
3245
3246 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3247 }
3248 // Make id<P...> cast into an 'id' cast.
3249 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3250 if (CE->getType()->isObjCQualifiedIdType()) {
3251 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3252 userExpr = CE->getSubExpr();
3253 CastKind CK;
3254 if (userExpr->getType()->isIntegralType(*Context)) {
3255 CK = CK_IntegralToPointer;
3256 } else if (userExpr->getType()->isBlockPointerType()) {
3257 CK = CK_BlockPointerToObjCPointerCast;
3258 } else if (userExpr->getType()->isPointerType()) {
3259 CK = CK_CPointerToObjCPointerCast;
3260 } else {
3261 CK = CK_BitCast;
3262 }
3263 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3264 CK, userExpr);
3265 }
3266 }
3267 MsgExprs.push_back(userExpr);
3268 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3269 // out the argument in the original expression (since we aren't deleting
3270 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3271 //Exp->setArg(i, 0);
3272 }
3273 // Generate the funky cast.
3274 CastExpr *cast;
3275 SmallVector<QualType, 8> ArgTypes;
3276 QualType returnType;
3277
3278 // Push 'id' and 'SEL', the 2 implicit arguments.
3279 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3280 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3281 else
3282 ArgTypes.push_back(Context->getObjCIdType());
3283 ArgTypes.push_back(Context->getObjCSelType());
3284 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3285 // Push any user argument types.
3286 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3287 E = OMD->param_end(); PI != E; ++PI) {
3288 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3289 ? Context->getObjCIdType()
3290 : (*PI)->getType();
3291 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3292 (void)convertBlockPointerToFunctionPointer(t);
3293 ArgTypes.push_back(t);
3294 }
3295 returnType = Exp->getType();
3296 convertToUnqualifiedObjCType(returnType);
3297 (void)convertBlockPointerToFunctionPointer(returnType);
3298 } else {
3299 returnType = Context->getObjCIdType();
3300 }
3301 // Get the type, we will need to reference it in a couple spots.
3302 QualType msgSendType = MsgSendFlavor->getType();
3303
3304 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003305 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003306 VK_LValue, SourceLocation());
3307
3308 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3309 // If we don't do this cast, we get the following bizarre warning/note:
3310 // xx.m:13: warning: function called through a non-compatible type
3311 // xx.m:13: note: if this code is reached, the program will abort
3312 cast = NoTypeInfoCStyleCastExpr(Context,
3313 Context->getPointerType(Context->VoidTy),
3314 CK_BitCast, DRE);
3315
3316 // Now do the "normal" pointer to function cast.
3317 QualType castType =
3318 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3319 // If we don't have a method decl, force a variadic cast.
3320 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3321 castType = Context->getPointerType(castType);
3322 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3323 cast);
3324
3325 // Don't forget the parens to enforce the proper binding.
3326 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3327
3328 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3329 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3330 MsgExprs.size(),
3331 FT->getResultType(), VK_RValue,
3332 EndLoc);
3333 Stmt *ReplacingStmt = CE;
3334 if (MsgSendStretFlavor) {
3335 // We have the method which returns a struct/union. Must also generate
3336 // call to objc_msgSend_stret and hang both varieties on a conditional
3337 // expression which dictate which one to envoke depending on size of
3338 // method's return type.
3339
3340 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003341 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3342 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003343 VK_LValue, SourceLocation());
3344 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3345 cast = NoTypeInfoCStyleCastExpr(Context,
3346 Context->getPointerType(Context->VoidTy),
3347 CK_BitCast, STDRE);
3348 // Now do the "normal" pointer to function cast.
3349 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3350 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3351 castType = Context->getPointerType(castType);
3352 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3353 cast);
3354
3355 // Don't forget the parens to enforce the proper binding.
3356 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3357
3358 FT = msgSendType->getAs<FunctionType>();
3359 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3360 MsgExprs.size(),
3361 FT->getResultType(), VK_RValue,
3362 SourceLocation());
3363
3364 // Build sizeof(returnType)
3365 UnaryExprOrTypeTraitExpr *sizeofExpr =
3366 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3367 Context->getTrivialTypeSourceInfo(returnType),
3368 Context->getSizeType(), SourceLocation(),
3369 SourceLocation());
3370 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3371 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3372 // For X86 it is more complicated and some kind of target specific routine
3373 // is needed to decide what to do.
3374 unsigned IntSize =
3375 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3376 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3377 llvm::APInt(IntSize, 8),
3378 Context->IntTy,
3379 SourceLocation());
3380 BinaryOperator *lessThanExpr =
3381 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3382 VK_RValue, OK_Ordinary, SourceLocation());
3383 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3384 ConditionalOperator *CondExpr =
3385 new (Context) ConditionalOperator(lessThanExpr,
3386 SourceLocation(), CE,
3387 SourceLocation(), STCE,
3388 returnType, VK_RValue, OK_Ordinary);
3389 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3390 CondExpr);
3391 }
3392 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3393 return ReplacingStmt;
3394}
3395
3396Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3397 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3398 Exp->getLocEnd());
3399
3400 // Now do the actual rewrite.
3401 ReplaceStmt(Exp, ReplacingStmt);
3402
3403 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3404 return ReplacingStmt;
3405}
3406
3407// typedef struct objc_object Protocol;
3408QualType RewriteModernObjC::getProtocolType() {
3409 if (!ProtocolTypeDecl) {
3410 TypeSourceInfo *TInfo
3411 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3412 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3413 SourceLocation(), SourceLocation(),
3414 &Context->Idents.get("Protocol"),
3415 TInfo);
3416 }
3417 return Context->getTypeDeclType(ProtocolTypeDecl);
3418}
3419
3420/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3421/// a synthesized/forward data reference (to the protocol's metadata).
3422/// The forward references (and metadata) are generated in
3423/// RewriteModernObjC::HandleTranslationUnit().
3424Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003425 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3426 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003427 IdentifierInfo *ID = &Context->Idents.get(Name);
3428 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3429 SourceLocation(), ID, getProtocolType(), 0,
3430 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003431 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3432 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003433 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3434 Context->getPointerType(DRE->getType()),
3435 VK_RValue, OK_Ordinary, SourceLocation());
3436 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3437 CK_BitCast,
3438 DerefExpr);
3439 ReplaceStmt(Exp, castExpr);
3440 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3441 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3442 return castExpr;
3443
3444}
3445
3446bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3447 const char *endBuf) {
3448 while (startBuf < endBuf) {
3449 if (*startBuf == '#') {
3450 // Skip whitespace.
3451 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3452 ;
3453 if (!strncmp(startBuf, "if", strlen("if")) ||
3454 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3455 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3456 !strncmp(startBuf, "define", strlen("define")) ||
3457 !strncmp(startBuf, "undef", strlen("undef")) ||
3458 !strncmp(startBuf, "else", strlen("else")) ||
3459 !strncmp(startBuf, "elif", strlen("elif")) ||
3460 !strncmp(startBuf, "endif", strlen("endif")) ||
3461 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3462 !strncmp(startBuf, "include", strlen("include")) ||
3463 !strncmp(startBuf, "import", strlen("import")) ||
3464 !strncmp(startBuf, "include_next", strlen("include_next")))
3465 return true;
3466 }
3467 startBuf++;
3468 }
3469 return false;
3470}
3471
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003472/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003473/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003474bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3475 std::string &Result) {
3476 if (Type->isArrayType()) {
3477 QualType ElemTy = Context->getBaseElementType(Type);
3478 return RewriteObjCFieldDeclType(ElemTy, Result);
3479 }
3480 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003481 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3482 if (RD->isCompleteDefinition()) {
3483 if (RD->isStruct())
3484 Result += "\n\tstruct ";
3485 else if (RD->isUnion())
3486 Result += "\n\tunion ";
3487 else
3488 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003489
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003490 Result += RD->getName();
3491 if (TagsDefinedInIvarDecls.count(RD)) {
3492 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003493 Result += " ";
3494 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003495 }
3496 TagsDefinedInIvarDecls.insert(RD);
3497 Result += " {\n";
3498 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003499 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003500 FieldDecl *FD = *i;
3501 RewriteObjCFieldDecl(FD, Result);
3502 }
3503 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003504 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003505 }
3506 }
3507 else if (Type->isEnumeralType()) {
3508 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3509 if (ED->isCompleteDefinition()) {
3510 Result += "\n\tenum ";
3511 Result += ED->getName();
3512 if (TagsDefinedInIvarDecls.count(ED)) {
3513 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003514 Result += " ";
3515 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003516 }
3517 TagsDefinedInIvarDecls.insert(ED);
3518
3519 Result += " {\n";
3520 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3521 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3522 Result += "\t"; Result += EC->getName(); Result += " = ";
3523 llvm::APSInt Val = EC->getInitVal();
3524 Result += Val.toString(10);
3525 Result += ",\n";
3526 }
3527 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003528 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003529 }
3530 }
3531
3532 Result += "\t";
3533 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003534 return false;
3535}
3536
3537
3538/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3539/// It handles elaborated types, as well as enum types in the process.
3540void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3541 std::string &Result) {
3542 QualType Type = fieldDecl->getType();
3543 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003544
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003545 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3546 if (!EleboratedType)
3547 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003548 Result += Name;
3549 if (fieldDecl->isBitField()) {
3550 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3551 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003552 else if (EleboratedType && Type->isArrayType()) {
3553 CanQualType CType = Context->getCanonicalType(Type);
3554 while (isa<ArrayType>(CType)) {
3555 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3556 Result += "[";
3557 llvm::APInt Dim = CAT->getSize();
3558 Result += utostr(Dim.getZExtValue());
3559 Result += "]";
3560 }
3561 CType = CType->getAs<ArrayType>()->getElementType();
3562 }
3563 }
3564
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003565 Result += ";\n";
3566}
3567
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003568/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3569/// an objective-c class with ivars.
3570void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3571 std::string &Result) {
3572 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3573 assert(CDecl->getName() != "" &&
3574 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003575 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003576 SmallVector<ObjCIvarDecl *, 8> IVars;
3577 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003578 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003579 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003580
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003581 SourceLocation LocStart = CDecl->getLocStart();
3582 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003583
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003584 const char *startBuf = SM->getCharacterData(LocStart);
3585 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003586
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003587 // If no ivars and no root or if its root, directly or indirectly,
3588 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003589 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003590 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3591 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3592 ReplaceText(LocStart, endBuf-startBuf, Result);
3593 return;
3594 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003595
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003596 Result += "\nstruct ";
3597 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003598 Result += "_IMPL {\n";
3599
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003600 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003601 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3602 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3603 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003604 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003605 TagsDefinedInIvarDecls.clear();
3606 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3607 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003608
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003609 Result += "};\n";
3610 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3611 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003612 // Mark this struct as having been generated.
3613 if (!ObjCSynthesizedStructs.insert(CDecl))
3614 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003615}
3616
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003617static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3618 ObjCIvarDecl *IvarDecl, std::string &Result) {
3619 Result += "OBJC_IVAR_$_";
3620 Result += IDecl->getName();
3621 Result += "$";
3622 Result += IvarDecl->getName();
3623}
3624
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003625/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3626/// have been referenced in an ivar access expression.
3627void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3628 std::string &Result) {
3629 // write out ivar offset symbols which have been referenced in an ivar
3630 // access expression.
3631 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3632 if (Ivars.empty())
3633 return;
3634 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3635 e = Ivars.end(); i != e; i++) {
3636 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003637 Result += "\n";
3638 if (LangOpts.MicrosoftExt)
3639 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003640 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003641 if (LangOpts.MicrosoftExt &&
3642 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003643 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3644 Result += "__declspec(dllimport) ";
3645
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003646 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003647 WriteInternalIvarName(CDecl, IvarDecl, Result);
3648 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003649 }
3650}
3651
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003652//===----------------------------------------------------------------------===//
3653// Meta Data Emission
3654//===----------------------------------------------------------------------===//
3655
3656
3657/// RewriteImplementations - This routine rewrites all method implementations
3658/// and emits meta-data.
3659
3660void RewriteModernObjC::RewriteImplementations() {
3661 int ClsDefCount = ClassImplementation.size();
3662 int CatDefCount = CategoryImplementation.size();
3663
3664 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003665 for (int i = 0; i < ClsDefCount; i++) {
3666 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3667 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3668 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003669 assert(false &&
3670 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003671 RewriteImplementationDecl(OIMP);
3672 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003673
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003674 for (int i = 0; i < CatDefCount; i++) {
3675 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3676 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3677 if (CDecl->isImplicitInterfaceDecl())
3678 assert(false &&
3679 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003680 RewriteImplementationDecl(CIMP);
3681 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003682}
3683
3684void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3685 const std::string &Name,
3686 ValueDecl *VD, bool def) {
3687 assert(BlockByRefDeclNo.count(VD) &&
3688 "RewriteByRefString: ByRef decl missing");
3689 if (def)
3690 ResultStr += "struct ";
3691 ResultStr += "__Block_byref_" + Name +
3692 "_" + utostr(BlockByRefDeclNo[VD]) ;
3693}
3694
3695static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3696 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3697 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3698 return false;
3699}
3700
3701std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3702 StringRef funcName,
3703 std::string Tag) {
3704 const FunctionType *AFT = CE->getFunctionType();
3705 QualType RT = AFT->getResultType();
3706 std::string StructRef = "struct " + Tag;
3707 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003708 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003709
3710 BlockDecl *BD = CE->getBlockDecl();
3711
3712 if (isa<FunctionNoProtoType>(AFT)) {
3713 // No user-supplied arguments. Still need to pass in a pointer to the
3714 // block (to reference imported block decl refs).
3715 S += "(" + StructRef + " *__cself)";
3716 } else if (BD->param_empty()) {
3717 S += "(" + StructRef + " *__cself)";
3718 } else {
3719 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3720 assert(FT && "SynthesizeBlockFunc: No function proto");
3721 S += '(';
3722 // first add the implicit argument.
3723 S += StructRef + " *__cself, ";
3724 std::string ParamStr;
3725 for (BlockDecl::param_iterator AI = BD->param_begin(),
3726 E = BD->param_end(); AI != E; ++AI) {
3727 if (AI != BD->param_begin()) S += ", ";
3728 ParamStr = (*AI)->getNameAsString();
3729 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003730 (void)convertBlockPointerToFunctionPointer(QT);
3731 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003732 S += ParamStr;
3733 }
3734 if (FT->isVariadic()) {
3735 if (!BD->param_empty()) S += ", ";
3736 S += "...";
3737 }
3738 S += ')';
3739 }
3740 S += " {\n";
3741
3742 // Create local declarations to avoid rewriting all closure decl ref exprs.
3743 // First, emit a declaration for all "by ref" decls.
3744 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3745 E = BlockByRefDecls.end(); I != E; ++I) {
3746 S += " ";
3747 std::string Name = (*I)->getNameAsString();
3748 std::string TypeString;
3749 RewriteByRefString(TypeString, Name, (*I));
3750 TypeString += " *";
3751 Name = TypeString + Name;
3752 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3753 }
3754 // Next, emit a declaration for all "by copy" declarations.
3755 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3756 E = BlockByCopyDecls.end(); I != E; ++I) {
3757 S += " ";
3758 // Handle nested closure invocation. For example:
3759 //
3760 // void (^myImportedClosure)(void);
3761 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3762 //
3763 // void (^anotherClosure)(void);
3764 // anotherClosure = ^(void) {
3765 // myImportedClosure(); // import and invoke the closure
3766 // };
3767 //
3768 if (isTopLevelBlockPointerType((*I)->getType())) {
3769 RewriteBlockPointerTypeVariable(S, (*I));
3770 S += " = (";
3771 RewriteBlockPointerType(S, (*I)->getType());
3772 S += ")";
3773 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3774 }
3775 else {
3776 std::string Name = (*I)->getNameAsString();
3777 QualType QT = (*I)->getType();
3778 if (HasLocalVariableExternalStorage(*I))
3779 QT = Context->getPointerType(QT);
3780 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3781 S += Name + " = __cself->" +
3782 (*I)->getNameAsString() + "; // bound by copy\n";
3783 }
3784 }
3785 std::string RewrittenStr = RewrittenBlockExprs[CE];
3786 const char *cstr = RewrittenStr.c_str();
3787 while (*cstr++ != '{') ;
3788 S += cstr;
3789 S += "\n";
3790 return S;
3791}
3792
3793std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3794 StringRef funcName,
3795 std::string Tag) {
3796 std::string StructRef = "struct " + Tag;
3797 std::string S = "static void __";
3798
3799 S += funcName;
3800 S += "_block_copy_" + utostr(i);
3801 S += "(" + StructRef;
3802 S += "*dst, " + StructRef;
3803 S += "*src) {";
3804 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3805 E = ImportedBlockDecls.end(); I != E; ++I) {
3806 ValueDecl *VD = (*I);
3807 S += "_Block_object_assign((void*)&dst->";
3808 S += (*I)->getNameAsString();
3809 S += ", (void*)src->";
3810 S += (*I)->getNameAsString();
3811 if (BlockByRefDeclsPtrSet.count((*I)))
3812 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3813 else if (VD->getType()->isBlockPointerType())
3814 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3815 else
3816 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3817 }
3818 S += "}\n";
3819
3820 S += "\nstatic void __";
3821 S += funcName;
3822 S += "_block_dispose_" + utostr(i);
3823 S += "(" + StructRef;
3824 S += "*src) {";
3825 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3826 E = ImportedBlockDecls.end(); I != E; ++I) {
3827 ValueDecl *VD = (*I);
3828 S += "_Block_object_dispose((void*)src->";
3829 S += (*I)->getNameAsString();
3830 if (BlockByRefDeclsPtrSet.count((*I)))
3831 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3832 else if (VD->getType()->isBlockPointerType())
3833 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3834 else
3835 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3836 }
3837 S += "}\n";
3838 return S;
3839}
3840
3841std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3842 std::string Desc) {
3843 std::string S = "\nstruct " + Tag;
3844 std::string Constructor = " " + Tag;
3845
3846 S += " {\n struct __block_impl impl;\n";
3847 S += " struct " + Desc;
3848 S += "* Desc;\n";
3849
3850 Constructor += "(void *fp, "; // Invoke function pointer.
3851 Constructor += "struct " + Desc; // Descriptor pointer.
3852 Constructor += " *desc";
3853
3854 if (BlockDeclRefs.size()) {
3855 // Output all "by copy" declarations.
3856 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3857 E = BlockByCopyDecls.end(); I != E; ++I) {
3858 S += " ";
3859 std::string FieldName = (*I)->getNameAsString();
3860 std::string ArgName = "_" + FieldName;
3861 // Handle nested closure invocation. For example:
3862 //
3863 // void (^myImportedBlock)(void);
3864 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3865 //
3866 // void (^anotherBlock)(void);
3867 // anotherBlock = ^(void) {
3868 // myImportedBlock(); // import and invoke the closure
3869 // };
3870 //
3871 if (isTopLevelBlockPointerType((*I)->getType())) {
3872 S += "struct __block_impl *";
3873 Constructor += ", void *" + ArgName;
3874 } else {
3875 QualType QT = (*I)->getType();
3876 if (HasLocalVariableExternalStorage(*I))
3877 QT = Context->getPointerType(QT);
3878 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3879 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3880 Constructor += ", " + ArgName;
3881 }
3882 S += FieldName + ";\n";
3883 }
3884 // Output all "by ref" declarations.
3885 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3886 E = BlockByRefDecls.end(); I != E; ++I) {
3887 S += " ";
3888 std::string FieldName = (*I)->getNameAsString();
3889 std::string ArgName = "_" + FieldName;
3890 {
3891 std::string TypeString;
3892 RewriteByRefString(TypeString, FieldName, (*I));
3893 TypeString += " *";
3894 FieldName = TypeString + FieldName;
3895 ArgName = TypeString + ArgName;
3896 Constructor += ", " + ArgName;
3897 }
3898 S += FieldName + "; // by ref\n";
3899 }
3900 // Finish writing the constructor.
3901 Constructor += ", int flags=0)";
3902 // Initialize all "by copy" arguments.
3903 bool firsTime = true;
3904 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3905 E = BlockByCopyDecls.end(); I != E; ++I) {
3906 std::string Name = (*I)->getNameAsString();
3907 if (firsTime) {
3908 Constructor += " : ";
3909 firsTime = false;
3910 }
3911 else
3912 Constructor += ", ";
3913 if (isTopLevelBlockPointerType((*I)->getType()))
3914 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3915 else
3916 Constructor += Name + "(_" + Name + ")";
3917 }
3918 // Initialize all "by ref" arguments.
3919 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3920 E = BlockByRefDecls.end(); I != E; ++I) {
3921 std::string Name = (*I)->getNameAsString();
3922 if (firsTime) {
3923 Constructor += " : ";
3924 firsTime = false;
3925 }
3926 else
3927 Constructor += ", ";
3928 Constructor += Name + "(_" + Name + "->__forwarding)";
3929 }
3930
3931 Constructor += " {\n";
3932 if (GlobalVarDecl)
3933 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3934 else
3935 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3936 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3937
3938 Constructor += " Desc = desc;\n";
3939 } else {
3940 // Finish writing the constructor.
3941 Constructor += ", int flags=0) {\n";
3942 if (GlobalVarDecl)
3943 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3944 else
3945 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3946 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3947 Constructor += " Desc = desc;\n";
3948 }
3949 Constructor += " ";
3950 Constructor += "}\n";
3951 S += Constructor;
3952 S += "};\n";
3953 return S;
3954}
3955
3956std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3957 std::string ImplTag, int i,
3958 StringRef FunName,
3959 unsigned hasCopy) {
3960 std::string S = "\nstatic struct " + DescTag;
3961
3962 S += " {\n unsigned long reserved;\n";
3963 S += " unsigned long Block_size;\n";
3964 if (hasCopy) {
3965 S += " void (*copy)(struct ";
3966 S += ImplTag; S += "*, struct ";
3967 S += ImplTag; S += "*);\n";
3968
3969 S += " void (*dispose)(struct ";
3970 S += ImplTag; S += "*);\n";
3971 }
3972 S += "} ";
3973
3974 S += DescTag + "_DATA = { 0, sizeof(struct ";
3975 S += ImplTag + ")";
3976 if (hasCopy) {
3977 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3978 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3979 }
3980 S += "};\n";
3981 return S;
3982}
3983
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00003984/// getFunctionSourceLocation - returns start location of a function
3985/// definition. Complication arises when function has declared as
3986/// extern "C" or extern "C" {...}
3987static SourceLocation getFunctionSourceLocation (FunctionDecl *FD) {
3988 if (!FD->isExternC() || FD->isMain())
3989 return FD->getTypeSpecStartLoc();
3990 const DeclContext *DC = FD->getDeclContext();
3991 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
3992 SourceLocation BodyRBrace = LSD->getRBraceLoc();
3993 // if it is extern "C" {...}, return function decl's own location.
3994 if (BodyRBrace.isValid())
3995 return FD->getTypeSpecStartLoc();
3996 return LSD->getExternLoc();
3997 }
3998 return FD->getTypeSpecStartLoc();
3999}
4000
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004001void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4002 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004003 bool RewriteSC = (GlobalVarDecl &&
4004 !Blocks.empty() &&
4005 GlobalVarDecl->getStorageClass() == SC_Static &&
4006 GlobalVarDecl->getType().getCVRQualifiers());
4007 if (RewriteSC) {
4008 std::string SC(" void __");
4009 SC += GlobalVarDecl->getNameAsString();
4010 SC += "() {}";
4011 InsertText(FunLocStart, SC);
4012 }
4013
4014 // Insert closures that were part of the function.
4015 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4016 CollectBlockDeclRefInfo(Blocks[i]);
4017 // Need to copy-in the inner copied-in variables not actually used in this
4018 // block.
4019 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004020 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004021 ValueDecl *VD = Exp->getDecl();
4022 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004023 if (!VD->hasAttr<BlocksAttr>()) {
4024 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4025 BlockByCopyDeclsPtrSet.insert(VD);
4026 BlockByCopyDecls.push_back(VD);
4027 }
4028 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004029 }
John McCallf4b88a42012-03-10 09:33:50 +00004030
4031 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004032 BlockByRefDeclsPtrSet.insert(VD);
4033 BlockByRefDecls.push_back(VD);
4034 }
John McCallf4b88a42012-03-10 09:33:50 +00004035
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004036 // imported objects in the inner blocks not used in the outer
4037 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004038 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004039 VD->getType()->isBlockPointerType())
4040 ImportedBlockDecls.insert(VD);
4041 }
4042
4043 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4044 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4045
4046 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4047
4048 InsertText(FunLocStart, CI);
4049
4050 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4051
4052 InsertText(FunLocStart, CF);
4053
4054 if (ImportedBlockDecls.size()) {
4055 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4056 InsertText(FunLocStart, HF);
4057 }
4058 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4059 ImportedBlockDecls.size() > 0);
4060 InsertText(FunLocStart, BD);
4061
4062 BlockDeclRefs.clear();
4063 BlockByRefDecls.clear();
4064 BlockByRefDeclsPtrSet.clear();
4065 BlockByCopyDecls.clear();
4066 BlockByCopyDeclsPtrSet.clear();
4067 ImportedBlockDecls.clear();
4068 }
4069 if (RewriteSC) {
4070 // Must insert any 'const/volatile/static here. Since it has been
4071 // removed as result of rewriting of block literals.
4072 std::string SC;
4073 if (GlobalVarDecl->getStorageClass() == SC_Static)
4074 SC = "static ";
4075 if (GlobalVarDecl->getType().isConstQualified())
4076 SC += "const ";
4077 if (GlobalVarDecl->getType().isVolatileQualified())
4078 SC += "volatile ";
4079 if (GlobalVarDecl->getType().isRestrictQualified())
4080 SC += "restrict ";
4081 InsertText(FunLocStart, SC);
4082 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004083 if (GlobalConstructionExp) {
4084 // extra fancy dance for global literal expression.
4085
4086 // Always the latest block expression on the block stack.
4087 std::string Tag = "__";
4088 Tag += FunName;
4089 Tag += "_block_impl_";
4090 Tag += utostr(Blocks.size()-1);
4091 std::string globalBuf = "static ";
4092 globalBuf += Tag; globalBuf += " ";
4093 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004094
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004095 llvm::raw_string_ostream constructorExprBuf(SStr);
4096 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4097 PrintingPolicy(LangOpts));
4098 globalBuf += constructorExprBuf.str();
4099 globalBuf += ";\n";
4100 InsertText(FunLocStart, globalBuf);
4101 GlobalConstructionExp = 0;
4102 }
4103
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004104 Blocks.clear();
4105 InnerDeclRefsCount.clear();
4106 InnerDeclRefs.clear();
4107 RewrittenBlockExprs.clear();
4108}
4109
4110void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004111 SourceLocation FunLocStart = getFunctionSourceLocation(FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004112 StringRef FuncName = FD->getName();
4113
4114 SynthesizeBlockLiterals(FunLocStart, FuncName);
4115}
4116
4117static void BuildUniqueMethodName(std::string &Name,
4118 ObjCMethodDecl *MD) {
4119 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4120 Name = IFace->getName();
4121 Name += "__" + MD->getSelector().getAsString();
4122 // Convert colons to underscores.
4123 std::string::size_type loc = 0;
4124 while ((loc = Name.find(":", loc)) != std::string::npos)
4125 Name.replace(loc, 1, "_");
4126}
4127
4128void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4129 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4130 //SourceLocation FunLocStart = MD->getLocStart();
4131 SourceLocation FunLocStart = MD->getLocStart();
4132 std::string FuncName;
4133 BuildUniqueMethodName(FuncName, MD);
4134 SynthesizeBlockLiterals(FunLocStart, FuncName);
4135}
4136
4137void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4138 for (Stmt::child_range CI = S->children(); CI; ++CI)
4139 if (*CI) {
4140 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4141 GetBlockDeclRefExprs(CBE->getBody());
4142 else
4143 GetBlockDeclRefExprs(*CI);
4144 }
4145 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004146 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4147 if (DRE->refersToEnclosingLocal()) {
4148 // FIXME: Handle enums.
4149 if (!isa<FunctionDecl>(DRE->getDecl()))
4150 BlockDeclRefs.push_back(DRE);
4151 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4152 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004153 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004154 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004155
4156 return;
4157}
4158
4159void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004160 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004161 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4162 for (Stmt::child_range CI = S->children(); CI; ++CI)
4163 if (*CI) {
4164 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4165 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4166 GetInnerBlockDeclRefExprs(CBE->getBody(),
4167 InnerBlockDeclRefs,
4168 InnerContexts);
4169 }
4170 else
4171 GetInnerBlockDeclRefExprs(*CI,
4172 InnerBlockDeclRefs,
4173 InnerContexts);
4174
4175 }
4176 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004177 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4178 if (DRE->refersToEnclosingLocal()) {
4179 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4180 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4181 InnerBlockDeclRefs.push_back(DRE);
4182 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4183 if (Var->isFunctionOrMethodVarDecl())
4184 ImportedLocalExternalDecls.insert(Var);
4185 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004186 }
4187
4188 return;
4189}
4190
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004191/// convertObjCTypeToCStyleType - This routine converts such objc types
4192/// as qualified objects, and blocks to their closest c/c++ types that
4193/// it can. It returns true if input type was modified.
4194bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4195 QualType oldT = T;
4196 convertBlockPointerToFunctionPointer(T);
4197 if (T->isFunctionPointerType()) {
4198 QualType PointeeTy;
4199 if (const PointerType* PT = T->getAs<PointerType>()) {
4200 PointeeTy = PT->getPointeeType();
4201 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4202 T = convertFunctionTypeOfBlocks(FT);
4203 T = Context->getPointerType(T);
4204 }
4205 }
4206 }
4207
4208 convertToUnqualifiedObjCType(T);
4209 return T != oldT;
4210}
4211
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004212/// convertFunctionTypeOfBlocks - This routine converts a function type
4213/// whose result type may be a block pointer or whose argument type(s)
4214/// might be block pointers to an equivalent function type replacing
4215/// all block pointers to function pointers.
4216QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4217 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4218 // FTP will be null for closures that don't take arguments.
4219 // Generate a funky cast.
4220 SmallVector<QualType, 8> ArgTypes;
4221 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004222 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004223
4224 if (FTP) {
4225 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4226 E = FTP->arg_type_end(); I && (I != E); ++I) {
4227 QualType t = *I;
4228 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004229 if (convertObjCTypeToCStyleType(t))
4230 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004231 ArgTypes.push_back(t);
4232 }
4233 }
4234 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004235 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004236 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4237 else FuncType = QualType(FT, 0);
4238 return FuncType;
4239}
4240
4241Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4242 // Navigate to relevant type information.
4243 const BlockPointerType *CPT = 0;
4244
4245 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4246 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004247 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4248 CPT = MExpr->getType()->getAs<BlockPointerType>();
4249 }
4250 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4251 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4252 }
4253 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4254 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4255 else if (const ConditionalOperator *CEXPR =
4256 dyn_cast<ConditionalOperator>(BlockExp)) {
4257 Expr *LHSExp = CEXPR->getLHS();
4258 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4259 Expr *RHSExp = CEXPR->getRHS();
4260 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4261 Expr *CONDExp = CEXPR->getCond();
4262 ConditionalOperator *CondExpr =
4263 new (Context) ConditionalOperator(CONDExp,
4264 SourceLocation(), cast<Expr>(LHSStmt),
4265 SourceLocation(), cast<Expr>(RHSStmt),
4266 Exp->getType(), VK_RValue, OK_Ordinary);
4267 return CondExpr;
4268 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4269 CPT = IRE->getType()->getAs<BlockPointerType>();
4270 } else if (const PseudoObjectExpr *POE
4271 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4272 CPT = POE->getType()->castAs<BlockPointerType>();
4273 } else {
4274 assert(1 && "RewriteBlockClass: Bad type");
4275 }
4276 assert(CPT && "RewriteBlockClass: Bad type");
4277 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4278 assert(FT && "RewriteBlockClass: Bad type");
4279 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4280 // FTP will be null for closures that don't take arguments.
4281
4282 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4283 SourceLocation(), SourceLocation(),
4284 &Context->Idents.get("__block_impl"));
4285 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4286
4287 // Generate a funky cast.
4288 SmallVector<QualType, 8> ArgTypes;
4289
4290 // Push the block argument type.
4291 ArgTypes.push_back(PtrBlock);
4292 if (FTP) {
4293 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4294 E = FTP->arg_type_end(); I && (I != E); ++I) {
4295 QualType t = *I;
4296 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4297 if (!convertBlockPointerToFunctionPointer(t))
4298 convertToUnqualifiedObjCType(t);
4299 ArgTypes.push_back(t);
4300 }
4301 }
4302 // Now do the pointer to function cast.
4303 QualType PtrToFuncCastType
4304 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4305
4306 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4307
4308 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4309 CK_BitCast,
4310 const_cast<Expr*>(BlockExp));
4311 // Don't forget the parens to enforce the proper binding.
4312 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4313 BlkCast);
4314 //PE->dump();
4315
4316 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4317 SourceLocation(),
4318 &Context->Idents.get("FuncPtr"),
4319 Context->VoidPtrTy, 0,
4320 /*BitWidth=*/0, /*Mutable=*/true,
4321 /*HasInit=*/false);
4322 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4323 FD->getType(), VK_LValue,
4324 OK_Ordinary);
4325
4326
4327 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4328 CK_BitCast, ME);
4329 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4330
4331 SmallVector<Expr*, 8> BlkExprs;
4332 // Add the implicit argument.
4333 BlkExprs.push_back(BlkCast);
4334 // Add the user arguments.
4335 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4336 E = Exp->arg_end(); I != E; ++I) {
4337 BlkExprs.push_back(*I);
4338 }
4339 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4340 BlkExprs.size(),
4341 Exp->getType(), VK_RValue,
4342 SourceLocation());
4343 return CE;
4344}
4345
4346// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004347// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004348// For example:
4349//
4350// int main() {
4351// __block Foo *f;
4352// __block int i;
4353//
4354// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004355// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004356// i = 77;
4357// };
4358//}
John McCallf4b88a42012-03-10 09:33:50 +00004359Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004360 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4361 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004362 ValueDecl *VD = DeclRefExp->getDecl();
4363 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004364
4365 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4366 SourceLocation(),
4367 &Context->Idents.get("__forwarding"),
4368 Context->VoidPtrTy, 0,
4369 /*BitWidth=*/0, /*Mutable=*/true,
4370 /*HasInit=*/false);
4371 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4372 FD, SourceLocation(),
4373 FD->getType(), VK_LValue,
4374 OK_Ordinary);
4375
4376 StringRef Name = VD->getName();
4377 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4378 &Context->Idents.get(Name),
4379 Context->VoidPtrTy, 0,
4380 /*BitWidth=*/0, /*Mutable=*/true,
4381 /*HasInit=*/false);
4382 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4383 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4384
4385
4386
4387 // Need parens to enforce precedence.
4388 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4389 DeclRefExp->getExprLoc(),
4390 ME);
4391 ReplaceStmt(DeclRefExp, PE);
4392 return PE;
4393}
4394
4395// Rewrites the imported local variable V with external storage
4396// (static, extern, etc.) as *V
4397//
4398Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4399 ValueDecl *VD = DRE->getDecl();
4400 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4401 if (!ImportedLocalExternalDecls.count(Var))
4402 return DRE;
4403 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4404 VK_LValue, OK_Ordinary,
4405 DRE->getLocation());
4406 // Need parens to enforce precedence.
4407 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4408 Exp);
4409 ReplaceStmt(DRE, PE);
4410 return PE;
4411}
4412
4413void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4414 SourceLocation LocStart = CE->getLParenLoc();
4415 SourceLocation LocEnd = CE->getRParenLoc();
4416
4417 // Need to avoid trying to rewrite synthesized casts.
4418 if (LocStart.isInvalid())
4419 return;
4420 // Need to avoid trying to rewrite casts contained in macros.
4421 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4422 return;
4423
4424 const char *startBuf = SM->getCharacterData(LocStart);
4425 const char *endBuf = SM->getCharacterData(LocEnd);
4426 QualType QT = CE->getType();
4427 const Type* TypePtr = QT->getAs<Type>();
4428 if (isa<TypeOfExprType>(TypePtr)) {
4429 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4430 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4431 std::string TypeAsString = "(";
4432 RewriteBlockPointerType(TypeAsString, QT);
4433 TypeAsString += ")";
4434 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4435 return;
4436 }
4437 // advance the location to startArgList.
4438 const char *argPtr = startBuf;
4439
4440 while (*argPtr++ && (argPtr < endBuf)) {
4441 switch (*argPtr) {
4442 case '^':
4443 // Replace the '^' with '*'.
4444 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4445 ReplaceText(LocStart, 1, "*");
4446 break;
4447 }
4448 }
4449 return;
4450}
4451
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004452void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4453 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004454 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4455 CastKind != CK_AnyPointerToBlockPointerCast)
4456 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004457
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004458 QualType QT = IC->getType();
4459 (void)convertBlockPointerToFunctionPointer(QT);
4460 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4461 std::string Str = "(";
4462 Str += TypeString;
4463 Str += ")";
4464 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4465
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004466 return;
4467}
4468
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004469void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4470 SourceLocation DeclLoc = FD->getLocation();
4471 unsigned parenCount = 0;
4472
4473 // We have 1 or more arguments that have closure pointers.
4474 const char *startBuf = SM->getCharacterData(DeclLoc);
4475 const char *startArgList = strchr(startBuf, '(');
4476
4477 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4478
4479 parenCount++;
4480 // advance the location to startArgList.
4481 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4482 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4483
4484 const char *argPtr = startArgList;
4485
4486 while (*argPtr++ && parenCount) {
4487 switch (*argPtr) {
4488 case '^':
4489 // Replace the '^' with '*'.
4490 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4491 ReplaceText(DeclLoc, 1, "*");
4492 break;
4493 case '(':
4494 parenCount++;
4495 break;
4496 case ')':
4497 parenCount--;
4498 break;
4499 }
4500 }
4501 return;
4502}
4503
4504bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4505 const FunctionProtoType *FTP;
4506 const PointerType *PT = QT->getAs<PointerType>();
4507 if (PT) {
4508 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4509 } else {
4510 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4511 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4512 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4513 }
4514 if (FTP) {
4515 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4516 E = FTP->arg_type_end(); I != E; ++I)
4517 if (isTopLevelBlockPointerType(*I))
4518 return true;
4519 }
4520 return false;
4521}
4522
4523bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4524 const FunctionProtoType *FTP;
4525 const PointerType *PT = QT->getAs<PointerType>();
4526 if (PT) {
4527 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4528 } else {
4529 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4530 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4531 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4532 }
4533 if (FTP) {
4534 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4535 E = FTP->arg_type_end(); I != E; ++I) {
4536 if ((*I)->isObjCQualifiedIdType())
4537 return true;
4538 if ((*I)->isObjCObjectPointerType() &&
4539 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4540 return true;
4541 }
4542
4543 }
4544 return false;
4545}
4546
4547void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4548 const char *&RParen) {
4549 const char *argPtr = strchr(Name, '(');
4550 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4551
4552 LParen = argPtr; // output the start.
4553 argPtr++; // skip past the left paren.
4554 unsigned parenCount = 1;
4555
4556 while (*argPtr && parenCount) {
4557 switch (*argPtr) {
4558 case '(': parenCount++; break;
4559 case ')': parenCount--; break;
4560 default: break;
4561 }
4562 if (parenCount) argPtr++;
4563 }
4564 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4565 RParen = argPtr; // output the end
4566}
4567
4568void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4569 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4570 RewriteBlockPointerFunctionArgs(FD);
4571 return;
4572 }
4573 // Handle Variables and Typedefs.
4574 SourceLocation DeclLoc = ND->getLocation();
4575 QualType DeclT;
4576 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4577 DeclT = VD->getType();
4578 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4579 DeclT = TDD->getUnderlyingType();
4580 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4581 DeclT = FD->getType();
4582 else
4583 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4584
4585 const char *startBuf = SM->getCharacterData(DeclLoc);
4586 const char *endBuf = startBuf;
4587 // scan backward (from the decl location) for the end of the previous decl.
4588 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4589 startBuf--;
4590 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4591 std::string buf;
4592 unsigned OrigLength=0;
4593 // *startBuf != '^' if we are dealing with a pointer to function that
4594 // may take block argument types (which will be handled below).
4595 if (*startBuf == '^') {
4596 // Replace the '^' with '*', computing a negative offset.
4597 buf = '*';
4598 startBuf++;
4599 OrigLength++;
4600 }
4601 while (*startBuf != ')') {
4602 buf += *startBuf;
4603 startBuf++;
4604 OrigLength++;
4605 }
4606 buf += ')';
4607 OrigLength++;
4608
4609 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4610 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4611 // Replace the '^' with '*' for arguments.
4612 // Replace id<P> with id/*<>*/
4613 DeclLoc = ND->getLocation();
4614 startBuf = SM->getCharacterData(DeclLoc);
4615 const char *argListBegin, *argListEnd;
4616 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4617 while (argListBegin < argListEnd) {
4618 if (*argListBegin == '^')
4619 buf += '*';
4620 else if (*argListBegin == '<') {
4621 buf += "/*";
4622 buf += *argListBegin++;
4623 OrigLength++;;
4624 while (*argListBegin != '>') {
4625 buf += *argListBegin++;
4626 OrigLength++;
4627 }
4628 buf += *argListBegin;
4629 buf += "*/";
4630 }
4631 else
4632 buf += *argListBegin;
4633 argListBegin++;
4634 OrigLength++;
4635 }
4636 buf += ')';
4637 OrigLength++;
4638 }
4639 ReplaceText(Start, OrigLength, buf);
4640
4641 return;
4642}
4643
4644
4645/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4646/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4647/// struct Block_byref_id_object *src) {
4648/// _Block_object_assign (&_dest->object, _src->object,
4649/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4650/// [|BLOCK_FIELD_IS_WEAK]) // object
4651/// _Block_object_assign(&_dest->object, _src->object,
4652/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4653/// [|BLOCK_FIELD_IS_WEAK]) // block
4654/// }
4655/// And:
4656/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4657/// _Block_object_dispose(_src->object,
4658/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4659/// [|BLOCK_FIELD_IS_WEAK]) // object
4660/// _Block_object_dispose(_src->object,
4661/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4662/// [|BLOCK_FIELD_IS_WEAK]) // block
4663/// }
4664
4665std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4666 int flag) {
4667 std::string S;
4668 if (CopyDestroyCache.count(flag))
4669 return S;
4670 CopyDestroyCache.insert(flag);
4671 S = "static void __Block_byref_id_object_copy_";
4672 S += utostr(flag);
4673 S += "(void *dst, void *src) {\n";
4674
4675 // offset into the object pointer is computed as:
4676 // void * + void* + int + int + void* + void *
4677 unsigned IntSize =
4678 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4679 unsigned VoidPtrSize =
4680 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4681
4682 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4683 S += " _Block_object_assign((char*)dst + ";
4684 S += utostr(offset);
4685 S += ", *(void * *) ((char*)src + ";
4686 S += utostr(offset);
4687 S += "), ";
4688 S += utostr(flag);
4689 S += ");\n}\n";
4690
4691 S += "static void __Block_byref_id_object_dispose_";
4692 S += utostr(flag);
4693 S += "(void *src) {\n";
4694 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4695 S += utostr(offset);
4696 S += "), ";
4697 S += utostr(flag);
4698 S += ");\n}\n";
4699 return S;
4700}
4701
4702/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4703/// the declaration into:
4704/// struct __Block_byref_ND {
4705/// void *__isa; // NULL for everything except __weak pointers
4706/// struct __Block_byref_ND *__forwarding;
4707/// int32_t __flags;
4708/// int32_t __size;
4709/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4710/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4711/// typex ND;
4712/// };
4713///
4714/// It then replaces declaration of ND variable with:
4715/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4716/// __size=sizeof(struct __Block_byref_ND),
4717/// ND=initializer-if-any};
4718///
4719///
4720void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004721 int flag = 0;
4722 int isa = 0;
4723 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4724 if (DeclLoc.isInvalid())
4725 // If type location is missing, it is because of missing type (a warning).
4726 // Use variable's location which is good for this case.
4727 DeclLoc = ND->getLocation();
4728 const char *startBuf = SM->getCharacterData(DeclLoc);
4729 SourceLocation X = ND->getLocEnd();
4730 X = SM->getExpansionLoc(X);
4731 const char *endBuf = SM->getCharacterData(X);
4732 std::string Name(ND->getNameAsString());
4733 std::string ByrefType;
4734 RewriteByRefString(ByrefType, Name, ND, true);
4735 ByrefType += " {\n";
4736 ByrefType += " void *__isa;\n";
4737 RewriteByRefString(ByrefType, Name, ND);
4738 ByrefType += " *__forwarding;\n";
4739 ByrefType += " int __flags;\n";
4740 ByrefType += " int __size;\n";
4741 // Add void *__Block_byref_id_object_copy;
4742 // void *__Block_byref_id_object_dispose; if needed.
4743 QualType Ty = ND->getType();
4744 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4745 if (HasCopyAndDispose) {
4746 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4747 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4748 }
4749
4750 QualType T = Ty;
4751 (void)convertBlockPointerToFunctionPointer(T);
4752 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4753
4754 ByrefType += " " + Name + ";\n";
4755 ByrefType += "};\n";
4756 // Insert this type in global scope. It is needed by helper function.
4757 SourceLocation FunLocStart;
4758 if (CurFunctionDef)
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004759 FunLocStart = getFunctionSourceLocation(CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004760 else {
4761 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4762 FunLocStart = CurMethodDef->getLocStart();
4763 }
4764 InsertText(FunLocStart, ByrefType);
4765 if (Ty.isObjCGCWeak()) {
4766 flag |= BLOCK_FIELD_IS_WEAK;
4767 isa = 1;
4768 }
4769
4770 if (HasCopyAndDispose) {
4771 flag = BLOCK_BYREF_CALLER;
4772 QualType Ty = ND->getType();
4773 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4774 if (Ty->isBlockPointerType())
4775 flag |= BLOCK_FIELD_IS_BLOCK;
4776 else
4777 flag |= BLOCK_FIELD_IS_OBJECT;
4778 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4779 if (!HF.empty())
4780 InsertText(FunLocStart, HF);
4781 }
4782
4783 // struct __Block_byref_ND ND =
4784 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4785 // initializer-if-any};
4786 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004787 // FIXME. rewriter does not support __block c++ objects which
4788 // require construction.
4789 if (hasInit && dyn_cast<CXXConstructExpr>(ND->getInit()))
4790 hasInit = false;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004791 unsigned flags = 0;
4792 if (HasCopyAndDispose)
4793 flags |= BLOCK_HAS_COPY_DISPOSE;
4794 Name = ND->getNameAsString();
4795 ByrefType.clear();
4796 RewriteByRefString(ByrefType, Name, ND);
4797 std::string ForwardingCastType("(");
4798 ForwardingCastType += ByrefType + " *)";
4799 if (!hasInit) {
4800 ByrefType += " " + Name + " = {(void*)";
4801 ByrefType += utostr(isa);
4802 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4803 ByrefType += utostr(flags);
4804 ByrefType += ", ";
4805 ByrefType += "sizeof(";
4806 RewriteByRefString(ByrefType, Name, ND);
4807 ByrefType += ")";
4808 if (HasCopyAndDispose) {
4809 ByrefType += ", __Block_byref_id_object_copy_";
4810 ByrefType += utostr(flag);
4811 ByrefType += ", __Block_byref_id_object_dispose_";
4812 ByrefType += utostr(flag);
4813 }
4814 ByrefType += "};\n";
4815 unsigned nameSize = Name.size();
4816 // for block or function pointer declaration. Name is aleady
4817 // part of the declaration.
4818 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4819 nameSize = 1;
4820 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4821 }
4822 else {
4823 SourceLocation startLoc;
4824 Expr *E = ND->getInit();
4825 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4826 startLoc = ECE->getLParenLoc();
4827 else
4828 startLoc = E->getLocStart();
4829 startLoc = SM->getExpansionLoc(startLoc);
4830 endBuf = SM->getCharacterData(startLoc);
4831 ByrefType += " " + Name;
4832 ByrefType += " = {(void*)";
4833 ByrefType += utostr(isa);
4834 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4835 ByrefType += utostr(flags);
4836 ByrefType += ", ";
4837 ByrefType += "sizeof(";
4838 RewriteByRefString(ByrefType, Name, ND);
4839 ByrefType += "), ";
4840 if (HasCopyAndDispose) {
4841 ByrefType += "__Block_byref_id_object_copy_";
4842 ByrefType += utostr(flag);
4843 ByrefType += ", __Block_byref_id_object_dispose_";
4844 ByrefType += utostr(flag);
4845 ByrefType += ", ";
4846 }
4847 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4848
4849 // Complete the newly synthesized compound expression by inserting a right
4850 // curly brace before the end of the declaration.
4851 // FIXME: This approach avoids rewriting the initializer expression. It
4852 // also assumes there is only one declarator. For example, the following
4853 // isn't currently supported by this routine (in general):
4854 //
4855 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4856 //
4857 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4858 const char *semiBuf = strchr(startInitializerBuf, ';');
4859 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4860 SourceLocation semiLoc =
4861 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4862
4863 InsertText(semiLoc, "}");
4864 }
4865 return;
4866}
4867
4868void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4869 // Add initializers for any closure decl refs.
4870 GetBlockDeclRefExprs(Exp->getBody());
4871 if (BlockDeclRefs.size()) {
4872 // Unique all "by copy" declarations.
4873 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004874 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004875 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4876 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4877 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4878 }
4879 }
4880 // Unique all "by ref" declarations.
4881 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004882 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004883 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4884 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4885 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4886 }
4887 }
4888 // Find any imported blocks...they will need special attention.
4889 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004890 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004891 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4892 BlockDeclRefs[i]->getType()->isBlockPointerType())
4893 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4894 }
4895}
4896
4897FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4898 IdentifierInfo *ID = &Context->Idents.get(name);
4899 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4900 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4901 SourceLocation(), ID, FType, 0, SC_Extern,
4902 SC_None, false, false);
4903}
4904
4905Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004906 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004907
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004908 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004909
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004910 Blocks.push_back(Exp);
4911
4912 CollectBlockDeclRefInfo(Exp);
4913
4914 // Add inner imported variables now used in current block.
4915 int countOfInnerDecls = 0;
4916 if (!InnerBlockDeclRefs.empty()) {
4917 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004918 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004919 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004920 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004921 // We need to save the copied-in variables in nested
4922 // blocks because it is needed at the end for some of the API generations.
4923 // See SynthesizeBlockLiterals routine.
4924 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4925 BlockDeclRefs.push_back(Exp);
4926 BlockByCopyDeclsPtrSet.insert(VD);
4927 BlockByCopyDecls.push_back(VD);
4928 }
John McCallf4b88a42012-03-10 09:33:50 +00004929 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004930 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4931 BlockDeclRefs.push_back(Exp);
4932 BlockByRefDeclsPtrSet.insert(VD);
4933 BlockByRefDecls.push_back(VD);
4934 }
4935 }
4936 // Find any imported blocks...they will need special attention.
4937 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004938 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004939 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4940 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4941 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4942 }
4943 InnerDeclRefsCount.push_back(countOfInnerDecls);
4944
4945 std::string FuncName;
4946
4947 if (CurFunctionDef)
4948 FuncName = CurFunctionDef->getNameAsString();
4949 else if (CurMethodDef)
4950 BuildUniqueMethodName(FuncName, CurMethodDef);
4951 else if (GlobalVarDecl)
4952 FuncName = std::string(GlobalVarDecl->getNameAsString());
4953
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004954 bool GlobalBlockExpr =
4955 block->getDeclContext()->getRedeclContext()->isFileContext();
4956
4957 if (GlobalBlockExpr && !GlobalVarDecl) {
4958 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4959 GlobalBlockExpr = false;
4960 }
4961
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004962 std::string BlockNumber = utostr(Blocks.size()-1);
4963
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004964 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4965
4966 // Get a pointer to the function type so we can cast appropriately.
4967 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4968 QualType FType = Context->getPointerType(BFT);
4969
4970 FunctionDecl *FD;
4971 Expr *NewRep;
4972
4973 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004974 std::string Tag;
4975
4976 if (GlobalBlockExpr)
4977 Tag = "__global_";
4978 else
4979 Tag = "__";
4980 Tag += FuncName + "_block_impl_" + BlockNumber;
4981
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004982 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004983 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004984 SourceLocation());
4985
4986 SmallVector<Expr*, 4> InitExprs;
4987
4988 // Initialize the block function.
4989 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004990 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4991 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004992 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4993 CK_BitCast, Arg);
4994 InitExprs.push_back(castExpr);
4995
4996 // Initialize the block descriptor.
4997 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4998
4999 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5000 SourceLocation(), SourceLocation(),
5001 &Context->Idents.get(DescData.c_str()),
5002 Context->VoidPtrTy, 0,
5003 SC_Static, SC_None);
5004 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005005 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005006 Context->VoidPtrTy,
5007 VK_LValue,
5008 SourceLocation()),
5009 UO_AddrOf,
5010 Context->getPointerType(Context->VoidPtrTy),
5011 VK_RValue, OK_Ordinary,
5012 SourceLocation());
5013 InitExprs.push_back(DescRefExpr);
5014
5015 // Add initializers for any closure decl refs.
5016 if (BlockDeclRefs.size()) {
5017 Expr *Exp;
5018 // Output all "by copy" declarations.
5019 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5020 E = BlockByCopyDecls.end(); I != E; ++I) {
5021 if (isObjCType((*I)->getType())) {
5022 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5023 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005024 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5025 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005026 if (HasLocalVariableExternalStorage(*I)) {
5027 QualType QT = (*I)->getType();
5028 QT = Context->getPointerType(QT);
5029 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5030 OK_Ordinary, SourceLocation());
5031 }
5032 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5033 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005034 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5035 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005036 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5037 CK_BitCast, Arg);
5038 } else {
5039 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005040 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5041 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005042 if (HasLocalVariableExternalStorage(*I)) {
5043 QualType QT = (*I)->getType();
5044 QT = Context->getPointerType(QT);
5045 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5046 OK_Ordinary, SourceLocation());
5047 }
5048
5049 }
5050 InitExprs.push_back(Exp);
5051 }
5052 // Output all "by ref" declarations.
5053 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5054 E = BlockByRefDecls.end(); I != E; ++I) {
5055 ValueDecl *ND = (*I);
5056 std::string Name(ND->getNameAsString());
5057 std::string RecName;
5058 RewriteByRefString(RecName, Name, ND, true);
5059 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5060 + sizeof("struct"));
5061 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5062 SourceLocation(), SourceLocation(),
5063 II);
5064 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5065 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5066
5067 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005068 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005069 SourceLocation());
5070 bool isNestedCapturedVar = false;
5071 if (block)
5072 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5073 ce = block->capture_end(); ci != ce; ++ci) {
5074 const VarDecl *variable = ci->getVariable();
5075 if (variable == ND && ci->isNested()) {
5076 assert (ci->isByRef() &&
5077 "SynthBlockInitExpr - captured block variable is not byref");
5078 isNestedCapturedVar = true;
5079 break;
5080 }
5081 }
5082 // captured nested byref variable has its address passed. Do not take
5083 // its address again.
5084 if (!isNestedCapturedVar)
5085 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5086 Context->getPointerType(Exp->getType()),
5087 VK_RValue, OK_Ordinary, SourceLocation());
5088 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5089 InitExprs.push_back(Exp);
5090 }
5091 }
5092 if (ImportedBlockDecls.size()) {
5093 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5094 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5095 unsigned IntSize =
5096 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5097 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5098 Context->IntTy, SourceLocation());
5099 InitExprs.push_back(FlagExp);
5100 }
5101 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5102 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005103
5104 if (GlobalBlockExpr) {
5105 assert (GlobalConstructionExp == 0 &&
5106 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5107 GlobalConstructionExp = NewRep;
5108 NewRep = DRE;
5109 }
5110
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005111 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5112 Context->getPointerType(NewRep->getType()),
5113 VK_RValue, OK_Ordinary, SourceLocation());
5114 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5115 NewRep);
5116 BlockDeclRefs.clear();
5117 BlockByRefDecls.clear();
5118 BlockByRefDeclsPtrSet.clear();
5119 BlockByCopyDecls.clear();
5120 BlockByCopyDeclsPtrSet.clear();
5121 ImportedBlockDecls.clear();
5122 return NewRep;
5123}
5124
5125bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5126 if (const ObjCForCollectionStmt * CS =
5127 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5128 return CS->getElement() == DS;
5129 return false;
5130}
5131
5132//===----------------------------------------------------------------------===//
5133// Function Body / Expression rewriting
5134//===----------------------------------------------------------------------===//
5135
5136Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5137 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5138 isa<DoStmt>(S) || isa<ForStmt>(S))
5139 Stmts.push_back(S);
5140 else if (isa<ObjCForCollectionStmt>(S)) {
5141 Stmts.push_back(S);
5142 ObjCBcLabelNo.push_back(++BcLabelCount);
5143 }
5144
5145 // Pseudo-object operations and ivar references need special
5146 // treatment because we're going to recursively rewrite them.
5147 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5148 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5149 return RewritePropertyOrImplicitSetter(PseudoOp);
5150 } else {
5151 return RewritePropertyOrImplicitGetter(PseudoOp);
5152 }
5153 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5154 return RewriteObjCIvarRefExpr(IvarRefExpr);
5155 }
5156
5157 SourceRange OrigStmtRange = S->getSourceRange();
5158
5159 // Perform a bottom up rewrite of all children.
5160 for (Stmt::child_range CI = S->children(); CI; ++CI)
5161 if (*CI) {
5162 Stmt *childStmt = (*CI);
5163 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5164 if (newStmt) {
5165 *CI = newStmt;
5166 }
5167 }
5168
5169 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005170 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005171 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5172 InnerContexts.insert(BE->getBlockDecl());
5173 ImportedLocalExternalDecls.clear();
5174 GetInnerBlockDeclRefExprs(BE->getBody(),
5175 InnerBlockDeclRefs, InnerContexts);
5176 // Rewrite the block body in place.
5177 Stmt *SaveCurrentBody = CurrentBody;
5178 CurrentBody = BE->getBody();
5179 PropParentMap = 0;
5180 // block literal on rhs of a property-dot-sytax assignment
5181 // must be replaced by its synthesize ast so getRewrittenText
5182 // works as expected. In this case, what actually ends up on RHS
5183 // is the blockTranscribed which is the helper function for the
5184 // block literal; as in: self.c = ^() {[ace ARR];};
5185 bool saveDisableReplaceStmt = DisableReplaceStmt;
5186 DisableReplaceStmt = false;
5187 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5188 DisableReplaceStmt = saveDisableReplaceStmt;
5189 CurrentBody = SaveCurrentBody;
5190 PropParentMap = 0;
5191 ImportedLocalExternalDecls.clear();
5192 // Now we snarf the rewritten text and stash it away for later use.
5193 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5194 RewrittenBlockExprs[BE] = Str;
5195
5196 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5197
5198 //blockTranscribed->dump();
5199 ReplaceStmt(S, blockTranscribed);
5200 return blockTranscribed;
5201 }
5202 // Handle specific things.
5203 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5204 return RewriteAtEncode(AtEncode);
5205
5206 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5207 return RewriteAtSelector(AtSelector);
5208
5209 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5210 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005211
5212 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5213 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005214
Patrick Beardeb382ec2012-04-19 00:25:12 +00005215 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5216 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005217
5218 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5219 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005220
5221 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5222 dyn_cast<ObjCDictionaryLiteral>(S))
5223 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005224
5225 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5226#if 0
5227 // Before we rewrite it, put the original message expression in a comment.
5228 SourceLocation startLoc = MessExpr->getLocStart();
5229 SourceLocation endLoc = MessExpr->getLocEnd();
5230
5231 const char *startBuf = SM->getCharacterData(startLoc);
5232 const char *endBuf = SM->getCharacterData(endLoc);
5233
5234 std::string messString;
5235 messString += "// ";
5236 messString.append(startBuf, endBuf-startBuf+1);
5237 messString += "\n";
5238
5239 // FIXME: Missing definition of
5240 // InsertText(clang::SourceLocation, char const*, unsigned int).
5241 // InsertText(startLoc, messString.c_str(), messString.size());
5242 // Tried this, but it didn't work either...
5243 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5244#endif
5245 return RewriteMessageExpr(MessExpr);
5246 }
5247
5248 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5249 return RewriteObjCTryStmt(StmtTry);
5250
5251 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5252 return RewriteObjCSynchronizedStmt(StmtTry);
5253
5254 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5255 return RewriteObjCThrowStmt(StmtThrow);
5256
5257 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5258 return RewriteObjCProtocolExpr(ProtocolExp);
5259
5260 if (ObjCForCollectionStmt *StmtForCollection =
5261 dyn_cast<ObjCForCollectionStmt>(S))
5262 return RewriteObjCForCollectionStmt(StmtForCollection,
5263 OrigStmtRange.getEnd());
5264 if (BreakStmt *StmtBreakStmt =
5265 dyn_cast<BreakStmt>(S))
5266 return RewriteBreakStmt(StmtBreakStmt);
5267 if (ContinueStmt *StmtContinueStmt =
5268 dyn_cast<ContinueStmt>(S))
5269 return RewriteContinueStmt(StmtContinueStmt);
5270
5271 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5272 // and cast exprs.
5273 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5274 // FIXME: What we're doing here is modifying the type-specifier that
5275 // precedes the first Decl. In the future the DeclGroup should have
5276 // a separate type-specifier that we can rewrite.
5277 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5278 // the context of an ObjCForCollectionStmt. For example:
5279 // NSArray *someArray;
5280 // for (id <FooProtocol> index in someArray) ;
5281 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5282 // and it depends on the original text locations/positions.
5283 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5284 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5285
5286 // Blocks rewrite rules.
5287 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5288 DI != DE; ++DI) {
5289 Decl *SD = *DI;
5290 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5291 if (isTopLevelBlockPointerType(ND->getType()))
5292 RewriteBlockPointerDecl(ND);
5293 else if (ND->getType()->isFunctionPointerType())
5294 CheckFunctionPointerDecl(ND->getType(), ND);
5295 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5296 if (VD->hasAttr<BlocksAttr>()) {
5297 static unsigned uniqueByrefDeclCount = 0;
5298 assert(!BlockByRefDeclNo.count(ND) &&
5299 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5300 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5301 RewriteByRefVar(VD);
5302 }
5303 else
5304 RewriteTypeOfDecl(VD);
5305 }
5306 }
5307 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5308 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5309 RewriteBlockPointerDecl(TD);
5310 else if (TD->getUnderlyingType()->isFunctionPointerType())
5311 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5312 }
5313 }
5314 }
5315
5316 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5317 RewriteObjCQualifiedInterfaceTypes(CE);
5318
5319 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5320 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5321 assert(!Stmts.empty() && "Statement stack is empty");
5322 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5323 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5324 && "Statement stack mismatch");
5325 Stmts.pop_back();
5326 }
5327 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005328 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5329 ValueDecl *VD = DRE->getDecl();
5330 if (VD->hasAttr<BlocksAttr>())
5331 return RewriteBlockDeclRefExpr(DRE);
5332 if (HasLocalVariableExternalStorage(VD))
5333 return RewriteLocalVariableExternalStorage(DRE);
5334 }
5335
5336 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5337 if (CE->getCallee()->getType()->isBlockPointerType()) {
5338 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5339 ReplaceStmt(S, BlockCall);
5340 return BlockCall;
5341 }
5342 }
5343 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5344 RewriteCastExpr(CE);
5345 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005346 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5347 RewriteImplicitCastObjCExpr(ICE);
5348 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005349#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005350
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005351 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5352 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5353 ICE->getSubExpr(),
5354 SourceLocation());
5355 // Get the new text.
5356 std::string SStr;
5357 llvm::raw_string_ostream Buf(SStr);
5358 Replacement->printPretty(Buf, *Context);
5359 const std::string &Str = Buf.str();
5360
5361 printf("CAST = %s\n", &Str[0]);
5362 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5363 delete S;
5364 return Replacement;
5365 }
5366#endif
5367 // Return this stmt unmodified.
5368 return S;
5369}
5370
5371void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5372 for (RecordDecl::field_iterator i = RD->field_begin(),
5373 e = RD->field_end(); i != e; ++i) {
5374 FieldDecl *FD = *i;
5375 if (isTopLevelBlockPointerType(FD->getType()))
5376 RewriteBlockPointerDecl(FD);
5377 if (FD->getType()->isObjCQualifiedIdType() ||
5378 FD->getType()->isObjCQualifiedInterfaceType())
5379 RewriteObjCQualifiedInterfaceTypes(FD);
5380 }
5381}
5382
5383/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5384/// main file of the input.
5385void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5386 switch (D->getKind()) {
5387 case Decl::Function: {
5388 FunctionDecl *FD = cast<FunctionDecl>(D);
5389 if (FD->isOverloadedOperator())
5390 return;
5391
5392 // Since function prototypes don't have ParmDecl's, we check the function
5393 // prototype. This enables us to rewrite function declarations and
5394 // definitions using the same code.
5395 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5396
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005397 if (!FD->isThisDeclarationADefinition())
5398 break;
5399
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005400 // FIXME: If this should support Obj-C++, support CXXTryStmt
5401 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5402 CurFunctionDef = FD;
5403 CurFunctionDeclToDeclareForBlock = FD;
5404 CurrentBody = Body;
5405 Body =
5406 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5407 FD->setBody(Body);
5408 CurrentBody = 0;
5409 if (PropParentMap) {
5410 delete PropParentMap;
5411 PropParentMap = 0;
5412 }
5413 // This synthesizes and inserts the block "impl" struct, invoke function,
5414 // and any copy/dispose helper functions.
5415 InsertBlockLiteralsWithinFunction(FD);
5416 CurFunctionDef = 0;
5417 CurFunctionDeclToDeclareForBlock = 0;
5418 }
5419 break;
5420 }
5421 case Decl::ObjCMethod: {
5422 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5423 if (CompoundStmt *Body = MD->getCompoundBody()) {
5424 CurMethodDef = MD;
5425 CurrentBody = Body;
5426 Body =
5427 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5428 MD->setBody(Body);
5429 CurrentBody = 0;
5430 if (PropParentMap) {
5431 delete PropParentMap;
5432 PropParentMap = 0;
5433 }
5434 InsertBlockLiteralsWithinMethod(MD);
5435 CurMethodDef = 0;
5436 }
5437 break;
5438 }
5439 case Decl::ObjCImplementation: {
5440 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5441 ClassImplementation.push_back(CI);
5442 break;
5443 }
5444 case Decl::ObjCCategoryImpl: {
5445 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5446 CategoryImplementation.push_back(CI);
5447 break;
5448 }
5449 case Decl::Var: {
5450 VarDecl *VD = cast<VarDecl>(D);
5451 RewriteObjCQualifiedInterfaceTypes(VD);
5452 if (isTopLevelBlockPointerType(VD->getType()))
5453 RewriteBlockPointerDecl(VD);
5454 else if (VD->getType()->isFunctionPointerType()) {
5455 CheckFunctionPointerDecl(VD->getType(), VD);
5456 if (VD->getInit()) {
5457 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5458 RewriteCastExpr(CE);
5459 }
5460 }
5461 } else if (VD->getType()->isRecordType()) {
5462 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5463 if (RD->isCompleteDefinition())
5464 RewriteRecordBody(RD);
5465 }
5466 if (VD->getInit()) {
5467 GlobalVarDecl = VD;
5468 CurrentBody = VD->getInit();
5469 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5470 CurrentBody = 0;
5471 if (PropParentMap) {
5472 delete PropParentMap;
5473 PropParentMap = 0;
5474 }
5475 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5476 GlobalVarDecl = 0;
5477
5478 // This is needed for blocks.
5479 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5480 RewriteCastExpr(CE);
5481 }
5482 }
5483 break;
5484 }
5485 case Decl::TypeAlias:
5486 case Decl::Typedef: {
5487 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5488 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5489 RewriteBlockPointerDecl(TD);
5490 else if (TD->getUnderlyingType()->isFunctionPointerType())
5491 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5492 }
5493 break;
5494 }
5495 case Decl::CXXRecord:
5496 case Decl::Record: {
5497 RecordDecl *RD = cast<RecordDecl>(D);
5498 if (RD->isCompleteDefinition())
5499 RewriteRecordBody(RD);
5500 break;
5501 }
5502 default:
5503 break;
5504 }
5505 // Nothing yet.
5506}
5507
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005508/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5509/// protocol reference symbols in the for of:
5510/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5511static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5512 ObjCProtocolDecl *PDecl,
5513 std::string &Result) {
5514 // Also output .objc_protorefs$B section and its meta-data.
5515 if (Context->getLangOpts().MicrosoftExt)
5516 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5517 Result += "struct _protocol_t *";
5518 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5519 Result += PDecl->getNameAsString();
5520 Result += " = &";
5521 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5522 Result += ";\n";
5523}
5524
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005525void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5526 if (Diags.hasErrorOccurred())
5527 return;
5528
5529 RewriteInclude();
5530
5531 // Here's a great place to add any extra declarations that may be needed.
5532 // Write out meta data for each @protocol(<expr>).
5533 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005534 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005535 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005536 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5537 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005538
5539 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005540 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5541 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5542 // Write struct declaration for the class matching its ivar declarations.
5543 // Note that for modern abi, this is postponed until the end of TU
5544 // because class extensions and the implementation might declare their own
5545 // private ivars.
5546 RewriteInterfaceDecl(CDecl);
5547 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005548
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005549 if (ClassImplementation.size() || CategoryImplementation.size())
5550 RewriteImplementations();
5551
5552 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5553 // we are done.
5554 if (const RewriteBuffer *RewriteBuf =
5555 Rewrite.getRewriteBufferFor(MainFileID)) {
5556 //printf("Changed:\n");
5557 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5558 } else {
5559 llvm::errs() << "No changes\n";
5560 }
5561
5562 if (ClassImplementation.size() || CategoryImplementation.size() ||
5563 ProtocolExprDecls.size()) {
5564 // Rewrite Objective-c meta data*
5565 std::string ResultStr;
5566 RewriteMetaDataIntoBuffer(ResultStr);
5567 // Emit metadata.
5568 *OutFile << ResultStr;
5569 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005570 // Emit ImageInfo;
5571 {
5572 std::string ResultStr;
5573 WriteImageInfo(ResultStr);
5574 *OutFile << ResultStr;
5575 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005576 OutFile->flush();
5577}
5578
5579void RewriteModernObjC::Initialize(ASTContext &context) {
5580 InitializeCommon(context);
5581
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005582 Preamble += "#ifndef __OBJC2__\n";
5583 Preamble += "#define __OBJC2__\n";
5584 Preamble += "#endif\n";
5585
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005586 // declaring objc_selector outside the parameter list removes a silly
5587 // scope related warning...
5588 if (IsHeader)
5589 Preamble = "#pragma once\n";
5590 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005591 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5592 Preamble += "\n\tstruct objc_object *superClass; ";
5593 // Add a constructor for creating temporary objects.
5594 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5595 Preamble += ": object(o), superClass(s) {} ";
5596 Preamble += "\n};\n";
5597
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005598 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005599 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005600 // These are currently generated.
5601 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005602 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005603 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005604 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5605 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005606 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005607 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005608 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005609 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5610 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005611 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005612
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005613 // These need be generated for performance. Currently they are not,
5614 // using API calls instead.
5615 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5616 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5617 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5618
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005619 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005620 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5621 Preamble += "typedef struct objc_object Protocol;\n";
5622 Preamble += "#define _REWRITER_typedef_Protocol\n";
5623 Preamble += "#endif\n";
5624 if (LangOpts.MicrosoftExt) {
5625 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5626 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005627 }
5628 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005629 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005630
5631 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5632 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5633 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5634 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5635 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5636
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005637 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5638 Preamble += "(const char *);\n";
5639 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5640 Preamble += "(struct objc_class *);\n";
5641 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5642 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005643 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005644 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005645 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5646 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005647 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5648 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5649 Preamble += "struct __objcFastEnumerationState {\n\t";
5650 Preamble += "unsigned long state;\n\t";
5651 Preamble += "void **itemsPtr;\n\t";
5652 Preamble += "unsigned long *mutationsPtr;\n\t";
5653 Preamble += "unsigned long extra[5];\n};\n";
5654 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5655 Preamble += "#define __FASTENUMERATIONSTATE\n";
5656 Preamble += "#endif\n";
5657 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5658 Preamble += "struct __NSConstantStringImpl {\n";
5659 Preamble += " int *isa;\n";
5660 Preamble += " int flags;\n";
5661 Preamble += " char *str;\n";
5662 Preamble += " long length;\n";
5663 Preamble += "};\n";
5664 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5665 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5666 Preamble += "#else\n";
5667 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5668 Preamble += "#endif\n";
5669 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5670 Preamble += "#endif\n";
5671 // Blocks preamble.
5672 Preamble += "#ifndef BLOCK_IMPL\n";
5673 Preamble += "#define BLOCK_IMPL\n";
5674 Preamble += "struct __block_impl {\n";
5675 Preamble += " void *isa;\n";
5676 Preamble += " int Flags;\n";
5677 Preamble += " int Reserved;\n";
5678 Preamble += " void *FuncPtr;\n";
5679 Preamble += "};\n";
5680 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5681 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5682 Preamble += "extern \"C\" __declspec(dllexport) "
5683 "void _Block_object_assign(void *, const void *, const int);\n";
5684 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5685 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5686 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5687 Preamble += "#else\n";
5688 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5689 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5690 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5691 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5692 Preamble += "#endif\n";
5693 Preamble += "#endif\n";
5694 if (LangOpts.MicrosoftExt) {
5695 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5696 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5697 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5698 Preamble += "#define __attribute__(X)\n";
5699 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005700 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005701 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005702 Preamble += "#endif\n";
5703 Preamble += "#ifndef __block\n";
5704 Preamble += "#define __block\n";
5705 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005706 }
5707 else {
5708 Preamble += "#define __block\n";
5709 Preamble += "#define __weak\n";
5710 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005711
5712 // Declarations required for modern objective-c array and dictionary literals.
5713 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005714 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005715 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005716 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005717 Preamble += "\tva_list marker;\n";
5718 Preamble += "\tva_start(marker, count);\n";
5719 Preamble += "\tarr = new void *[count];\n";
5720 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5721 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5722 Preamble += "\tva_end( marker );\n";
5723 Preamble += " };\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005724 Preamble += " __NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005725 Preamble += "\tdelete[] arr;\n";
5726 Preamble += " }\n";
5727 Preamble += "};\n";
5728
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005729 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5730 // as this avoids warning in any 64bit/32bit compilation model.
5731 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5732}
5733
5734/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5735/// ivar offset.
5736void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5737 std::string &Result) {
5738 if (ivar->isBitField()) {
5739 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5740 // place all bitfields at offset 0.
5741 Result += "0";
5742 } else {
5743 Result += "__OFFSETOFIVAR__(struct ";
5744 Result += ivar->getContainingInterface()->getNameAsString();
5745 if (LangOpts.MicrosoftExt)
5746 Result += "_IMPL";
5747 Result += ", ";
5748 Result += ivar->getNameAsString();
5749 Result += ")";
5750 }
5751}
5752
5753/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5754/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005755/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005756/// char *attributes;
5757/// }
5758
5759/// struct _prop_list_t {
5760/// uint32_t entsize; // sizeof(struct _prop_t)
5761/// uint32_t count_of_properties;
5762/// struct _prop_t prop_list[count_of_properties];
5763/// }
5764
5765/// struct _protocol_t;
5766
5767/// struct _protocol_list_t {
5768/// long protocol_count; // Note, this is 32/64 bit
5769/// struct _protocol_t * protocol_list[protocol_count];
5770/// }
5771
5772/// struct _objc_method {
5773/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005774/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005775/// char *_imp;
5776/// }
5777
5778/// struct _method_list_t {
5779/// uint32_t entsize; // sizeof(struct _objc_method)
5780/// uint32_t method_count;
5781/// struct _objc_method method_list[method_count];
5782/// }
5783
5784/// struct _protocol_t {
5785/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005786/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005787/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005788/// const struct method_list_t *instance_methods;
5789/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005790/// const struct method_list_t *optionalInstanceMethods;
5791/// const struct method_list_t *optionalClassMethods;
5792/// const struct _prop_list_t * properties;
5793/// const uint32_t size; // sizeof(struct _protocol_t)
5794/// const uint32_t flags; // = 0
5795/// const char ** extendedMethodTypes;
5796/// }
5797
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005798/// struct _ivar_t {
5799/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005800/// const char *name;
5801/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005802/// uint32_t alignment;
5803/// uint32_t size;
5804/// }
5805
5806/// struct _ivar_list_t {
5807/// uint32 entsize; // sizeof(struct _ivar_t)
5808/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005809/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005810/// }
5811
5812/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005813/// uint32_t flags;
5814/// uint32_t instanceStart;
5815/// uint32_t instanceSize;
5816/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005817/// const uint8_t *ivarLayout;
5818/// const char *name;
5819/// const struct _method_list_t *baseMethods;
5820/// const struct _protocol_list_t *baseProtocols;
5821/// const struct _ivar_list_t *ivars;
5822/// const uint8_t *weakIvarLayout;
5823/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005824/// }
5825
5826/// struct _class_t {
5827/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005828/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005829/// void *cache;
5830/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005831/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005832/// }
5833
5834/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005835/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005836/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005837/// const struct _method_list_t *instance_methods;
5838/// const struct _method_list_t *class_methods;
5839/// const struct _protocol_list_t *protocols;
5840/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005841/// }
5842
5843/// MessageRefTy - LLVM for:
5844/// struct _message_ref_t {
5845/// IMP messenger;
5846/// SEL name;
5847/// };
5848
5849/// SuperMessageRefTy - LLVM for:
5850/// struct _super_message_ref_t {
5851/// SUPER_IMP messenger;
5852/// SEL name;
5853/// };
5854
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005855static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005856 static bool meta_data_declared = false;
5857 if (meta_data_declared)
5858 return;
5859
5860 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005861 Result += "\tconst char *name;\n";
5862 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005863 Result += "};\n";
5864
5865 Result += "\nstruct _protocol_t;\n";
5866
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005867 Result += "\nstruct _objc_method {\n";
5868 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005869 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005870 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005871 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005872
5873 Result += "\nstruct _protocol_t {\n";
5874 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005875 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005876 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005877 Result += "\tconst struct method_list_t *instance_methods;\n";
5878 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005879 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5880 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5881 Result += "\tconst struct _prop_list_t * properties;\n";
5882 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5883 Result += "\tconst unsigned int flags; // = 0\n";
5884 Result += "\tconst char ** extendedMethodTypes;\n";
5885 Result += "};\n";
5886
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005887 Result += "\nstruct _ivar_t {\n";
5888 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005889 Result += "\tconst char *name;\n";
5890 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005891 Result += "\tunsigned int alignment;\n";
5892 Result += "\tunsigned int size;\n";
5893 Result += "};\n";
5894
5895 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005896 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005897 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005898 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005899 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5900 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005901 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005902 Result += "\tconst unsigned char *ivarLayout;\n";
5903 Result += "\tconst char *name;\n";
5904 Result += "\tconst struct _method_list_t *baseMethods;\n";
5905 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5906 Result += "\tconst struct _ivar_list_t *ivars;\n";
5907 Result += "\tconst unsigned char *weakIvarLayout;\n";
5908 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005909 Result += "};\n";
5910
5911 Result += "\nstruct _class_t {\n";
5912 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005913 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005914 Result += "\tvoid *cache;\n";
5915 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005916 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005917 Result += "};\n";
5918
5919 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005920 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005921 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005922 Result += "\tconst struct _method_list_t *instance_methods;\n";
5923 Result += "\tconst struct _method_list_t *class_methods;\n";
5924 Result += "\tconst struct _protocol_list_t *protocols;\n";
5925 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005926 Result += "};\n";
5927
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005928 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005929 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005930 meta_data_declared = true;
5931}
5932
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005933static void Write_protocol_list_t_TypeDecl(std::string &Result,
5934 long super_protocol_count) {
5935 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5936 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5937 Result += "\tstruct _protocol_t *super_protocols[";
5938 Result += utostr(super_protocol_count); Result += "];\n";
5939 Result += "}";
5940}
5941
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005942static void Write_method_list_t_TypeDecl(std::string &Result,
5943 unsigned int method_count) {
5944 Result += "struct /*_method_list_t*/"; Result += " {\n";
5945 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5946 Result += "\tunsigned int method_count;\n";
5947 Result += "\tstruct _objc_method method_list[";
5948 Result += utostr(method_count); Result += "];\n";
5949 Result += "}";
5950}
5951
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005952static void Write__prop_list_t_TypeDecl(std::string &Result,
5953 unsigned int property_count) {
5954 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5955 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5956 Result += "\tunsigned int count_of_properties;\n";
5957 Result += "\tstruct _prop_t prop_list[";
5958 Result += utostr(property_count); Result += "];\n";
5959 Result += "}";
5960}
5961
Fariborz Jahanianae932952012-02-10 20:47:10 +00005962static void Write__ivar_list_t_TypeDecl(std::string &Result,
5963 unsigned int ivar_count) {
5964 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5965 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5966 Result += "\tunsigned int count;\n";
5967 Result += "\tstruct _ivar_t ivar_list[";
5968 Result += utostr(ivar_count); Result += "];\n";
5969 Result += "}";
5970}
5971
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005972static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5973 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5974 StringRef VarName,
5975 StringRef ProtocolName) {
5976 if (SuperProtocols.size() > 0) {
5977 Result += "\nstatic ";
5978 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5979 Result += " "; Result += VarName;
5980 Result += ProtocolName;
5981 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5982 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5983 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5984 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5985 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5986 Result += SuperPD->getNameAsString();
5987 if (i == e-1)
5988 Result += "\n};\n";
5989 else
5990 Result += ",\n";
5991 }
5992 }
5993}
5994
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005995static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5996 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005997 ArrayRef<ObjCMethodDecl *> Methods,
5998 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005999 StringRef TopLevelDeclName,
6000 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006001 if (Methods.size() > 0) {
6002 Result += "\nstatic ";
6003 Write_method_list_t_TypeDecl(Result, Methods.size());
6004 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006005 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006006 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6007 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6008 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6009 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6010 ObjCMethodDecl *MD = Methods[i];
6011 if (i == 0)
6012 Result += "\t{{(struct objc_selector *)\"";
6013 else
6014 Result += "\t{(struct objc_selector *)\"";
6015 Result += (MD)->getSelector().getAsString(); Result += "\"";
6016 Result += ", ";
6017 std::string MethodTypeString;
6018 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6019 Result += "\""; Result += MethodTypeString; Result += "\"";
6020 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006021 if (!MethodImpl)
6022 Result += "0";
6023 else {
6024 Result += "(void *)";
6025 Result += RewriteObj.MethodInternalNames[MD];
6026 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006027 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006028 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006029 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006030 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006031 }
6032 Result += "};\n";
6033 }
6034}
6035
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006036static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006037 ASTContext *Context, std::string &Result,
6038 ArrayRef<ObjCPropertyDecl *> Properties,
6039 const Decl *Container,
6040 StringRef VarName,
6041 StringRef ProtocolName) {
6042 if (Properties.size() > 0) {
6043 Result += "\nstatic ";
6044 Write__prop_list_t_TypeDecl(Result, Properties.size());
6045 Result += " "; Result += VarName;
6046 Result += ProtocolName;
6047 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6048 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6049 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6050 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6051 ObjCPropertyDecl *PropDecl = Properties[i];
6052 if (i == 0)
6053 Result += "\t{{\"";
6054 else
6055 Result += "\t{\"";
6056 Result += PropDecl->getName(); Result += "\",";
6057 std::string PropertyTypeString, QuotePropertyTypeString;
6058 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6059 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6060 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6061 if (i == e-1)
6062 Result += "}}\n";
6063 else
6064 Result += "},\n";
6065 }
6066 Result += "};\n";
6067 }
6068}
6069
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006070// Metadata flags
6071enum MetaDataDlags {
6072 CLS = 0x0,
6073 CLS_META = 0x1,
6074 CLS_ROOT = 0x2,
6075 OBJC2_CLS_HIDDEN = 0x10,
6076 CLS_EXCEPTION = 0x20,
6077
6078 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6079 CLS_HAS_IVAR_RELEASER = 0x40,
6080 /// class was compiled with -fobjc-arr
6081 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6082};
6083
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006084static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6085 unsigned int flags,
6086 const std::string &InstanceStart,
6087 const std::string &InstanceSize,
6088 ArrayRef<ObjCMethodDecl *>baseMethods,
6089 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6090 ArrayRef<ObjCIvarDecl *>ivars,
6091 ArrayRef<ObjCPropertyDecl *>Properties,
6092 StringRef VarName,
6093 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006094 Result += "\nstatic struct _class_ro_t ";
6095 Result += VarName; Result += ClassName;
6096 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6097 Result += "\t";
6098 Result += llvm::utostr(flags); Result += ", ";
6099 Result += InstanceStart; Result += ", ";
6100 Result += InstanceSize; Result += ", \n";
6101 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006102 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6103 if (Triple.getArch() == llvm::Triple::x86_64)
6104 // uint32_t const reserved; // only when building for 64bit targets
6105 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006106 // const uint8_t * const ivarLayout;
6107 Result += "0, \n\t";
6108 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006109 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006110 if (baseMethods.size() > 0) {
6111 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006112 if (metaclass)
6113 Result += "_OBJC_$_CLASS_METHODS_";
6114 else
6115 Result += "_OBJC_$_INSTANCE_METHODS_";
6116 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006117 Result += ",\n\t";
6118 }
6119 else
6120 Result += "0, \n\t";
6121
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006122 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006123 Result += "(const struct _objc_protocol_list *)&";
6124 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6125 Result += ",\n\t";
6126 }
6127 else
6128 Result += "0, \n\t";
6129
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006130 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006131 Result += "(const struct _ivar_list_t *)&";
6132 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6133 Result += ",\n\t";
6134 }
6135 else
6136 Result += "0, \n\t";
6137
6138 // weakIvarLayout
6139 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006140 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006141 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006142 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006143 Result += ",\n";
6144 }
6145 else
6146 Result += "0, \n";
6147
6148 Result += "};\n";
6149}
6150
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006151static void Write_class_t(ASTContext *Context, std::string &Result,
6152 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006153 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6154 bool rootClass = (!CDecl->getSuperClass());
6155 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006156
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006157 if (!rootClass) {
6158 // Find the Root class
6159 RootClass = CDecl->getSuperClass();
6160 while (RootClass->getSuperClass()) {
6161 RootClass = RootClass->getSuperClass();
6162 }
6163 }
6164
6165 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006166 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006167 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006168 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006169 if (CDecl->getImplementation())
6170 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006171 else
6172 Result += "__declspec(dllimport) ";
6173
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006174 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006175 Result += CDecl->getNameAsString();
6176 Result += ";\n";
6177 }
6178 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006179 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006180 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006181 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006182 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006183 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006184 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006185 else
6186 Result += "__declspec(dllimport) ";
6187
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006188 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006189 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006190 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006191 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006192
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006193 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006194 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006195 if (RootClass->getImplementation())
6196 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006197 else
6198 Result += "__declspec(dllimport) ";
6199
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006200 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006201 Result += VarName;
6202 Result += RootClass->getNameAsString();
6203 Result += ";\n";
6204 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006205 }
6206
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006207 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6208 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006209 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6210 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006211 if (metaclass) {
6212 if (!rootClass) {
6213 Result += "0, // &"; Result += VarName;
6214 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006215 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006216 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006217 Result += CDecl->getSuperClass()->getNameAsString();
6218 Result += ",\n\t";
6219 }
6220 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006221 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006222 Result += CDecl->getNameAsString();
6223 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006224 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006225 Result += ",\n\t";
6226 }
6227 }
6228 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006229 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006230 Result += CDecl->getNameAsString();
6231 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006232 if (!rootClass) {
6233 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006234 Result += CDecl->getSuperClass()->getNameAsString();
6235 Result += ",\n\t";
6236 }
6237 else
6238 Result += "0,\n\t";
6239 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006240 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6241 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6242 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006243 Result += "&_OBJC_METACLASS_RO_$_";
6244 else
6245 Result += "&_OBJC_CLASS_RO_$_";
6246 Result += CDecl->getNameAsString();
6247 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006248
6249 // Add static function to initialize some of the meta-data fields.
6250 // avoid doing it twice.
6251 if (metaclass)
6252 return;
6253
6254 const ObjCInterfaceDecl *SuperClass =
6255 rootClass ? CDecl : CDecl->getSuperClass();
6256
6257 Result += "static void OBJC_CLASS_SETUP_$_";
6258 Result += CDecl->getNameAsString();
6259 Result += "(void ) {\n";
6260 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6261 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006262 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006263
6264 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006265 Result += ".superclass = ";
6266 if (rootClass)
6267 Result += "&OBJC_CLASS_$_";
6268 else
6269 Result += "&OBJC_METACLASS_$_";
6270
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006271 Result += SuperClass->getNameAsString(); Result += ";\n";
6272
6273 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6274 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6275
6276 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6277 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6278 Result += CDecl->getNameAsString(); Result += ";\n";
6279
6280 if (!rootClass) {
6281 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6282 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6283 Result += SuperClass->getNameAsString(); Result += ";\n";
6284 }
6285
6286 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6287 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6288 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006289}
6290
Fariborz Jahanian61186122012-02-17 18:40:41 +00006291static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6292 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006293 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006294 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006295 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6296 ArrayRef<ObjCMethodDecl *> ClassMethods,
6297 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6298 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006299 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006300 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006301 // must declare an extern class object in case this class is not implemented
6302 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006303 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006304 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006305 if (ClassDecl->getImplementation())
6306 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006307 else
6308 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006309
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006310 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006311 Result += "OBJC_CLASS_$_"; Result += ClassName;
6312 Result += ";\n";
6313
Fariborz Jahanian61186122012-02-17 18:40:41 +00006314 Result += "\nstatic struct _category_t ";
6315 Result += "_OBJC_$_CATEGORY_";
6316 Result += ClassName; Result += "_$_"; Result += CatName;
6317 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6318 Result += "{\n";
6319 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006320 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006321 Result += ",\n";
6322 if (InstanceMethods.size() > 0) {
6323 Result += "\t(const struct _method_list_t *)&";
6324 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6325 Result += ClassName; Result += "_$_"; Result += CatName;
6326 Result += ",\n";
6327 }
6328 else
6329 Result += "\t0,\n";
6330
6331 if (ClassMethods.size() > 0) {
6332 Result += "\t(const struct _method_list_t *)&";
6333 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6334 Result += ClassName; Result += "_$_"; Result += CatName;
6335 Result += ",\n";
6336 }
6337 else
6338 Result += "\t0,\n";
6339
6340 if (RefedProtocols.size() > 0) {
6341 Result += "\t(const struct _protocol_list_t *)&";
6342 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6343 Result += ClassName; Result += "_$_"; Result += CatName;
6344 Result += ",\n";
6345 }
6346 else
6347 Result += "\t0,\n";
6348
6349 if (ClassProperties.size() > 0) {
6350 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6351 Result += ClassName; Result += "_$_"; Result += CatName;
6352 Result += ",\n";
6353 }
6354 else
6355 Result += "\t0,\n";
6356
6357 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006358
6359 // Add static function to initialize the class pointer in the category structure.
6360 Result += "static void OBJC_CATEGORY_SETUP_$_";
6361 Result += ClassDecl->getNameAsString();
6362 Result += "_$_";
6363 Result += CatName;
6364 Result += "(void ) {\n";
6365 Result += "\t_OBJC_$_CATEGORY_";
6366 Result += ClassDecl->getNameAsString();
6367 Result += "_$_";
6368 Result += CatName;
6369 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6370 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006371}
6372
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006373static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6374 ASTContext *Context, std::string &Result,
6375 ArrayRef<ObjCMethodDecl *> Methods,
6376 StringRef VarName,
6377 StringRef ProtocolName) {
6378 if (Methods.size() == 0)
6379 return;
6380
6381 Result += "\nstatic const char *";
6382 Result += VarName; Result += ProtocolName;
6383 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6384 Result += "{\n";
6385 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6386 ObjCMethodDecl *MD = Methods[i];
6387 std::string MethodTypeString, QuoteMethodTypeString;
6388 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6389 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6390 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6391 if (i == e-1)
6392 Result += "\n};\n";
6393 else {
6394 Result += ",\n";
6395 }
6396 }
6397}
6398
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006399static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6400 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006401 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006402 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006403 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006404 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6405 // this is what happens:
6406 /**
6407 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6408 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6409 Class->getVisibility() == HiddenVisibility)
6410 Visibility shoud be: HiddenVisibility;
6411 else
6412 Visibility shoud be: DefaultVisibility;
6413 */
6414
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006415 Result += "\n";
6416 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6417 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006418 if (Context->getLangOpts().MicrosoftExt)
6419 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6420
6421 if (!Context->getLangOpts().MicrosoftExt ||
6422 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006423 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006424 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006425 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006426 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006427 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006428 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6429 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006430 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6431 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006432 }
6433}
6434
Fariborz Jahanianae932952012-02-10 20:47:10 +00006435static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6436 ASTContext *Context, std::string &Result,
6437 ArrayRef<ObjCIvarDecl *> Ivars,
6438 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006439 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006440 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006441 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006442
Fariborz Jahanianae932952012-02-10 20:47:10 +00006443 Result += "\nstatic ";
6444 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6445 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006446 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006447 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6448 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6449 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6450 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6451 ObjCIvarDecl *IvarDecl = Ivars[i];
6452 if (i == 0)
6453 Result += "\t{{";
6454 else
6455 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006456 Result += "(unsigned long int *)&";
6457 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006458 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006459
6460 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6461 std::string IvarTypeString, QuoteIvarTypeString;
6462 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6463 IvarDecl);
6464 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6465 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6466
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006467 // FIXME. this alignment represents the host alignment and need be changed to
6468 // represent the target alignment.
6469 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6470 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006471 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006472 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6473 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006474 if (i == e-1)
6475 Result += "}}\n";
6476 else
6477 Result += "},\n";
6478 }
6479 Result += "};\n";
6480 }
6481}
6482
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006483/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006484void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6485 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006486
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006487 // Do not synthesize the protocol more than once.
6488 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6489 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006490 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006491
6492 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6493 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006494 // Must write out all protocol definitions in current qualifier list,
6495 // and in their nested qualifiers before writing out current definition.
6496 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6497 E = PDecl->protocol_end(); I != E; ++I)
6498 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006499
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006500 // Construct method lists.
6501 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6502 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6503 for (ObjCProtocolDecl::instmeth_iterator
6504 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6505 I != E; ++I) {
6506 ObjCMethodDecl *MD = *I;
6507 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6508 OptInstanceMethods.push_back(MD);
6509 } else {
6510 InstanceMethods.push_back(MD);
6511 }
6512 }
6513
6514 for (ObjCProtocolDecl::classmeth_iterator
6515 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6516 I != E; ++I) {
6517 ObjCMethodDecl *MD = *I;
6518 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6519 OptClassMethods.push_back(MD);
6520 } else {
6521 ClassMethods.push_back(MD);
6522 }
6523 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006524 std::vector<ObjCMethodDecl *> AllMethods;
6525 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6526 AllMethods.push_back(InstanceMethods[i]);
6527 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6528 AllMethods.push_back(ClassMethods[i]);
6529 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6530 AllMethods.push_back(OptInstanceMethods[i]);
6531 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6532 AllMethods.push_back(OptClassMethods[i]);
6533
6534 Write__extendedMethodTypes_initializer(*this, Context, Result,
6535 AllMethods,
6536 "_OBJC_PROTOCOL_METHOD_TYPES_",
6537 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006538 // Protocol's super protocol list
6539 std::vector<ObjCProtocolDecl *> SuperProtocols;
6540 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6541 E = PDecl->protocol_end(); I != E; ++I)
6542 SuperProtocols.push_back(*I);
6543
6544 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6545 "_OBJC_PROTOCOL_REFS_",
6546 PDecl->getNameAsString());
6547
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006548 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006549 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006550 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006551
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006552 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006553 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006554 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006555
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006556 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006557 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006558 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006559
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006560 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006561 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006562 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006563
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006564 // Protocol's property metadata.
6565 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6566 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6567 E = PDecl->prop_end(); I != E; ++I)
6568 ProtocolProperties.push_back(*I);
6569
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006570 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006571 /* Container */0,
6572 "_OBJC_PROTOCOL_PROPERTIES_",
6573 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006574
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006575 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006576 Result += "\n";
6577 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006578 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006579 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006580 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006581 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6582 Result += "\t0,\n"; // id is; is null
6583 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006584 if (SuperProtocols.size() > 0) {
6585 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6586 Result += PDecl->getNameAsString(); Result += ",\n";
6587 }
6588 else
6589 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006590 if (InstanceMethods.size() > 0) {
6591 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6592 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006593 }
6594 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006595 Result += "\t0,\n";
6596
6597 if (ClassMethods.size() > 0) {
6598 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6599 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006600 }
6601 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006602 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006603
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006604 if (OptInstanceMethods.size() > 0) {
6605 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6606 Result += PDecl->getNameAsString(); Result += ",\n";
6607 }
6608 else
6609 Result += "\t0,\n";
6610
6611 if (OptClassMethods.size() > 0) {
6612 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6613 Result += PDecl->getNameAsString(); Result += ",\n";
6614 }
6615 else
6616 Result += "\t0,\n";
6617
6618 if (ProtocolProperties.size() > 0) {
6619 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6620 Result += PDecl->getNameAsString(); Result += ",\n";
6621 }
6622 else
6623 Result += "\t0,\n";
6624
6625 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6626 Result += "\t0,\n";
6627
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006628 if (AllMethods.size() > 0) {
6629 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6630 Result += PDecl->getNameAsString();
6631 Result += "\n};\n";
6632 }
6633 else
6634 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006635
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006636 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006637 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006638 Result += "struct _protocol_t *";
6639 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6640 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6641 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006642
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006643 // Mark this protocol as having been generated.
6644 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6645 llvm_unreachable("protocol already synthesized");
6646
6647}
6648
6649void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6650 const ObjCList<ObjCProtocolDecl> &Protocols,
6651 StringRef prefix, StringRef ClassName,
6652 std::string &Result) {
6653 if (Protocols.empty()) return;
6654
6655 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006656 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006657
6658 // Output the top lovel protocol meta-data for the class.
6659 /* struct _objc_protocol_list {
6660 struct _objc_protocol_list *next;
6661 int protocol_count;
6662 struct _objc_protocol *class_protocols[];
6663 }
6664 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006665 Result += "\n";
6666 if (LangOpts.MicrosoftExt)
6667 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6668 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006669 Result += "\tstruct _objc_protocol_list *next;\n";
6670 Result += "\tint protocol_count;\n";
6671 Result += "\tstruct _objc_protocol *class_protocols[";
6672 Result += utostr(Protocols.size());
6673 Result += "];\n} _OBJC_";
6674 Result += prefix;
6675 Result += "_PROTOCOLS_";
6676 Result += ClassName;
6677 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6678 "{\n\t0, ";
6679 Result += utostr(Protocols.size());
6680 Result += "\n";
6681
6682 Result += "\t,{&_OBJC_PROTOCOL_";
6683 Result += Protocols[0]->getNameAsString();
6684 Result += " \n";
6685
6686 for (unsigned i = 1; i != Protocols.size(); i++) {
6687 Result += "\t ,&_OBJC_PROTOCOL_";
6688 Result += Protocols[i]->getNameAsString();
6689 Result += "\n";
6690 }
6691 Result += "\t }\n};\n";
6692}
6693
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006694/// hasObjCExceptionAttribute - Return true if this class or any super
6695/// class has the __objc_exception__ attribute.
6696/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6697static bool hasObjCExceptionAttribute(ASTContext &Context,
6698 const ObjCInterfaceDecl *OID) {
6699 if (OID->hasAttr<ObjCExceptionAttr>())
6700 return true;
6701 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6702 return hasObjCExceptionAttribute(Context, Super);
6703 return false;
6704}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006705
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006706void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6707 std::string &Result) {
6708 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6709
6710 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006711 if (CDecl->isImplicitInterfaceDecl())
6712 assert(false &&
6713 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006714
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006715 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006716 SmallVector<ObjCIvarDecl *, 8> IVars;
6717
6718 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6719 IVD; IVD = IVD->getNextIvar()) {
6720 // Ignore unnamed bit-fields.
6721 if (!IVD->getDeclName())
6722 continue;
6723 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006724 }
6725
Fariborz Jahanianae932952012-02-10 20:47:10 +00006726 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006727 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006728 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006729
6730 // Build _objc_method_list for class's instance methods if needed
6731 SmallVector<ObjCMethodDecl *, 32>
6732 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6733
6734 // If any of our property implementations have associated getters or
6735 // setters, produce metadata for them as well.
6736 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6737 PropEnd = IDecl->propimpl_end();
6738 Prop != PropEnd; ++Prop) {
6739 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6740 continue;
6741 if (!(*Prop)->getPropertyIvarDecl())
6742 continue;
6743 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6744 if (!PD)
6745 continue;
6746 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6747 if (!Getter->isDefined())
6748 InstanceMethods.push_back(Getter);
6749 if (PD->isReadOnly())
6750 continue;
6751 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6752 if (!Setter->isDefined())
6753 InstanceMethods.push_back(Setter);
6754 }
6755
6756 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6757 "_OBJC_$_INSTANCE_METHODS_",
6758 IDecl->getNameAsString(), true);
6759
6760 SmallVector<ObjCMethodDecl *, 32>
6761 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6762
6763 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6764 "_OBJC_$_CLASS_METHODS_",
6765 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006766
6767 // Protocols referenced in class declaration?
6768 // Protocol's super protocol list
6769 std::vector<ObjCProtocolDecl *> RefedProtocols;
6770 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6771 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6772 E = Protocols.end();
6773 I != E; ++I) {
6774 RefedProtocols.push_back(*I);
6775 // Must write out all protocol definitions in current qualifier list,
6776 // and in their nested qualifiers before writing out current definition.
6777 RewriteObjCProtocolMetaData(*I, Result);
6778 }
6779
6780 Write_protocol_list_initializer(Context, Result,
6781 RefedProtocols,
6782 "_OBJC_CLASS_PROTOCOLS_$_",
6783 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006784
6785 // Protocol's property metadata.
6786 std::vector<ObjCPropertyDecl *> ClassProperties;
6787 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6788 E = CDecl->prop_end(); I != E; ++I)
6789 ClassProperties.push_back(*I);
6790
6791 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006792 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006793 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006794 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006795
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006796
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006797 // Data for initializing _class_ro_t metaclass meta-data
6798 uint32_t flags = CLS_META;
6799 std::string InstanceSize;
6800 std::string InstanceStart;
6801
6802
6803 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6804 if (classIsHidden)
6805 flags |= OBJC2_CLS_HIDDEN;
6806
6807 if (!CDecl->getSuperClass())
6808 // class is root
6809 flags |= CLS_ROOT;
6810 InstanceSize = "sizeof(struct _class_t)";
6811 InstanceStart = InstanceSize;
6812 Write__class_ro_t_initializer(Context, Result, flags,
6813 InstanceStart, InstanceSize,
6814 ClassMethods,
6815 0,
6816 0,
6817 0,
6818 "_OBJC_METACLASS_RO_$_",
6819 CDecl->getNameAsString());
6820
6821
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006822 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006823 flags = CLS;
6824 if (classIsHidden)
6825 flags |= OBJC2_CLS_HIDDEN;
6826
6827 if (hasObjCExceptionAttribute(*Context, CDecl))
6828 flags |= CLS_EXCEPTION;
6829
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006830 if (!CDecl->getSuperClass())
6831 // class is root
6832 flags |= CLS_ROOT;
6833
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006834 InstanceSize.clear();
6835 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006836 if (!ObjCSynthesizedStructs.count(CDecl)) {
6837 InstanceSize = "0";
6838 InstanceStart = "0";
6839 }
6840 else {
6841 InstanceSize = "sizeof(struct ";
6842 InstanceSize += CDecl->getNameAsString();
6843 InstanceSize += "_IMPL)";
6844
6845 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6846 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006847 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006848 }
6849 else
6850 InstanceStart = InstanceSize;
6851 }
6852 Write__class_ro_t_initializer(Context, Result, flags,
6853 InstanceStart, InstanceSize,
6854 InstanceMethods,
6855 RefedProtocols,
6856 IVars,
6857 ClassProperties,
6858 "_OBJC_CLASS_RO_$_",
6859 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006860
6861 Write_class_t(Context, Result,
6862 "OBJC_METACLASS_$_",
6863 CDecl, /*metaclass*/true);
6864
6865 Write_class_t(Context, Result,
6866 "OBJC_CLASS_$_",
6867 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006868
6869 if (ImplementationIsNonLazy(IDecl))
6870 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006871
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006872}
6873
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006874void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6875 int ClsDefCount = ClassImplementation.size();
6876 if (!ClsDefCount)
6877 return;
6878 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6879 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6880 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6881 for (int i = 0; i < ClsDefCount; i++) {
6882 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6883 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6884 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6885 Result += CDecl->getName(); Result += ",\n";
6886 }
6887 Result += "};\n";
6888}
6889
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006890void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6891 int ClsDefCount = ClassImplementation.size();
6892 int CatDefCount = CategoryImplementation.size();
6893
6894 // For each implemented class, write out all its meta data.
6895 for (int i = 0; i < ClsDefCount; i++)
6896 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6897
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006898 RewriteClassSetupInitHook(Result);
6899
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006900 // For each implemented category, write out all its meta data.
6901 for (int i = 0; i < CatDefCount; i++)
6902 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6903
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006904 RewriteCategorySetupInitHook(Result);
6905
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006906 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006907 if (LangOpts.MicrosoftExt)
6908 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006909 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6910 Result += llvm::utostr(ClsDefCount); Result += "]";
6911 Result +=
6912 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6913 "regular,no_dead_strip\")))= {\n";
6914 for (int i = 0; i < ClsDefCount; i++) {
6915 Result += "\t&OBJC_CLASS_$_";
6916 Result += ClassImplementation[i]->getNameAsString();
6917 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006918 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006919 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006920
6921 if (!DefinedNonLazyClasses.empty()) {
6922 if (LangOpts.MicrosoftExt)
6923 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6924 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6925 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6926 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6927 Result += ",\n";
6928 }
6929 Result += "};\n";
6930 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006931 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006932
6933 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006934 if (LangOpts.MicrosoftExt)
6935 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006936 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6937 Result += llvm::utostr(CatDefCount); Result += "]";
6938 Result +=
6939 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6940 "regular,no_dead_strip\")))= {\n";
6941 for (int i = 0; i < CatDefCount; i++) {
6942 Result += "\t&_OBJC_$_CATEGORY_";
6943 Result +=
6944 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6945 Result += "_$_";
6946 Result += CategoryImplementation[i]->getNameAsString();
6947 Result += ",\n";
6948 }
6949 Result += "};\n";
6950 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006951
6952 if (!DefinedNonLazyCategories.empty()) {
6953 if (LangOpts.MicrosoftExt)
6954 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6955 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6956 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6957 Result += "\t&_OBJC_$_CATEGORY_";
6958 Result +=
6959 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6960 Result += "_$_";
6961 Result += DefinedNonLazyCategories[i]->getNameAsString();
6962 Result += ",\n";
6963 }
6964 Result += "};\n";
6965 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006966}
6967
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006968void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6969 if (LangOpts.MicrosoftExt)
6970 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6971
6972 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6973 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006974 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006975}
6976
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006977/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6978/// implementation.
6979void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6980 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006981 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006982 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6983 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006984 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006985 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6986 CDecl = CDecl->getNextClassCategory())
6987 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6988 break;
6989
6990 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006991 FullCategoryName += "_$_";
6992 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006993
6994 // Build _objc_method_list for class's instance methods if needed
6995 SmallVector<ObjCMethodDecl *, 32>
6996 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6997
6998 // If any of our property implementations have associated getters or
6999 // setters, produce metadata for them as well.
7000 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7001 PropEnd = IDecl->propimpl_end();
7002 Prop != PropEnd; ++Prop) {
7003 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7004 continue;
7005 if (!(*Prop)->getPropertyIvarDecl())
7006 continue;
7007 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
7008 if (!PD)
7009 continue;
7010 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7011 InstanceMethods.push_back(Getter);
7012 if (PD->isReadOnly())
7013 continue;
7014 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7015 InstanceMethods.push_back(Setter);
7016 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007017
Fariborz Jahanian61186122012-02-17 18:40:41 +00007018 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7019 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7020 FullCategoryName, true);
7021
7022 SmallVector<ObjCMethodDecl *, 32>
7023 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7024
7025 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7026 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7027 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007028
7029 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007030 // Protocol's super protocol list
7031 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007032 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7033 E = CDecl->protocol_end();
7034
7035 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007036 RefedProtocols.push_back(*I);
7037 // Must write out all protocol definitions in current qualifier list,
7038 // and in their nested qualifiers before writing out current definition.
7039 RewriteObjCProtocolMetaData(*I, Result);
7040 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007041
Fariborz Jahanian61186122012-02-17 18:40:41 +00007042 Write_protocol_list_initializer(Context, Result,
7043 RefedProtocols,
7044 "_OBJC_CATEGORY_PROTOCOLS_$_",
7045 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007046
Fariborz Jahanian61186122012-02-17 18:40:41 +00007047 // Protocol's property metadata.
7048 std::vector<ObjCPropertyDecl *> ClassProperties;
7049 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7050 E = CDecl->prop_end(); I != E; ++I)
7051 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007052
Fariborz Jahanian61186122012-02-17 18:40:41 +00007053 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7054 /* Container */0,
7055 "_OBJC_$_PROP_LIST_",
7056 FullCategoryName);
7057
7058 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007059 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007060 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007061 InstanceMethods,
7062 ClassMethods,
7063 RefedProtocols,
7064 ClassProperties);
7065
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007066 // Determine if this category is also "non-lazy".
7067 if (ImplementationIsNonLazy(IDecl))
7068 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007069
7070}
7071
7072void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7073 int CatDefCount = CategoryImplementation.size();
7074 if (!CatDefCount)
7075 return;
7076 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7077 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7078 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7079 for (int i = 0; i < CatDefCount; i++) {
7080 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7081 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7082 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7083 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7084 Result += ClassDecl->getName();
7085 Result += "_$_";
7086 Result += CatDecl->getName();
7087 Result += ",\n";
7088 }
7089 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007090}
7091
7092// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7093/// class methods.
7094template<typename MethodIterator>
7095void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7096 MethodIterator MethodEnd,
7097 bool IsInstanceMethod,
7098 StringRef prefix,
7099 StringRef ClassName,
7100 std::string &Result) {
7101 if (MethodBegin == MethodEnd) return;
7102
7103 if (!objc_impl_method) {
7104 /* struct _objc_method {
7105 SEL _cmd;
7106 char *method_types;
7107 void *_imp;
7108 }
7109 */
7110 Result += "\nstruct _objc_method {\n";
7111 Result += "\tSEL _cmd;\n";
7112 Result += "\tchar *method_types;\n";
7113 Result += "\tvoid *_imp;\n";
7114 Result += "};\n";
7115
7116 objc_impl_method = true;
7117 }
7118
7119 // Build _objc_method_list for class's methods if needed
7120
7121 /* struct {
7122 struct _objc_method_list *next_method;
7123 int method_count;
7124 struct _objc_method method_list[];
7125 }
7126 */
7127 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007128 Result += "\n";
7129 if (LangOpts.MicrosoftExt) {
7130 if (IsInstanceMethod)
7131 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7132 else
7133 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7134 }
7135 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007136 Result += "\tstruct _objc_method_list *next_method;\n";
7137 Result += "\tint method_count;\n";
7138 Result += "\tstruct _objc_method method_list[";
7139 Result += utostr(NumMethods);
7140 Result += "];\n} _OBJC_";
7141 Result += prefix;
7142 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7143 Result += "_METHODS_";
7144 Result += ClassName;
7145 Result += " __attribute__ ((used, section (\"__OBJC, __";
7146 Result += IsInstanceMethod ? "inst" : "cls";
7147 Result += "_meth\")))= ";
7148 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7149
7150 Result += "\t,{{(SEL)\"";
7151 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7152 std::string MethodTypeString;
7153 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7154 Result += "\", \"";
7155 Result += MethodTypeString;
7156 Result += "\", (void *)";
7157 Result += MethodInternalNames[*MethodBegin];
7158 Result += "}\n";
7159 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7160 Result += "\t ,{(SEL)\"";
7161 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7162 std::string MethodTypeString;
7163 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7164 Result += "\", \"";
7165 Result += MethodTypeString;
7166 Result += "\", (void *)";
7167 Result += MethodInternalNames[*MethodBegin];
7168 Result += "}\n";
7169 }
7170 Result += "\t }\n};\n";
7171}
7172
7173Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7174 SourceRange OldRange = IV->getSourceRange();
7175 Expr *BaseExpr = IV->getBase();
7176
7177 // Rewrite the base, but without actually doing replaces.
7178 {
7179 DisableReplaceStmtScope S(*this);
7180 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7181 IV->setBase(BaseExpr);
7182 }
7183
7184 ObjCIvarDecl *D = IV->getDecl();
7185
7186 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007187
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007188 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7189 const ObjCInterfaceType *iFaceDecl =
7190 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7191 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7192 // lookup which class implements the instance variable.
7193 ObjCInterfaceDecl *clsDeclared = 0;
7194 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7195 clsDeclared);
7196 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7197
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007198 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007199 std::string IvarOffsetName;
7200 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7201
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007202 ReferencedIvars[clsDeclared].insert(D);
7203
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007204 // cast offset to "char *".
7205 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7206 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007207 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007208 BaseExpr);
7209 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7210 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7211 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007212 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7213 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007214 SourceLocation());
7215 BinaryOperator *addExpr =
7216 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7217 Context->getPointerType(Context->CharTy),
7218 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007219 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007220 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7221 SourceLocation(),
7222 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007223 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007224 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007225 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007226
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007227 castExpr = NoTypeInfoCStyleCastExpr(Context,
7228 castT,
7229 CK_BitCast,
7230 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007231 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007232 VK_LValue, OK_Ordinary,
7233 SourceLocation());
7234 PE = new (Context) ParenExpr(OldRange.getBegin(),
7235 OldRange.getEnd(),
7236 Exp);
7237
7238 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007239 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007240
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007241 ReplaceStmtWithRange(IV, Replacement, OldRange);
7242 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007243}