blob: aee89f11b2b62307bf4bda11af95f2cf7c5571b5 [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;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000111 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000113 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
114 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
115
116 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
117 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
118
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000119 SmallVector<Stmt *, 32> Stmts;
120 SmallVector<int, 8> ObjCBcLabelNo;
121 // Remember all the @protocol(<expr>) expressions.
122 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
123
124 llvm::DenseSet<uint64_t> CopyDestroyCache;
125
126 // Block expressions.
127 SmallVector<BlockExpr *, 32> Blocks;
128 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000129 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000130
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
133 // Block related declarations.
134 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
135 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
136 SmallVector<ValueDecl *, 8> BlockByRefDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
138 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
139 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
140 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
141
142 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000143 llvm::DenseMap<ObjCInterfaceDecl *,
144 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
145
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000146 // This maps an original source AST to it's rewritten form. This allows
147 // us to avoid rewriting the same node twice (which is very uncommon).
148 // This is needed to support some of the exotic property rewriting.
149 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
150
151 // Needed for header files being rewritten
152 bool IsHeader;
153 bool SilenceRewriteMacroWarning;
154 bool objc_impl_method;
155
156 bool DisableReplaceStmt;
157 class DisableReplaceStmtScope {
158 RewriteModernObjC &R;
159 bool SavedValue;
160
161 public:
162 DisableReplaceStmtScope(RewriteModernObjC &R)
163 : R(R), SavedValue(R.DisableReplaceStmt) {
164 R.DisableReplaceStmt = true;
165 }
166 ~DisableReplaceStmtScope() {
167 R.DisableReplaceStmt = SavedValue;
168 }
169 };
170 void InitializeCommon(ASTContext &context);
171
172 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000173 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000174 // Top Level Driver code.
175 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
176 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
177 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
178 if (!Class->isThisDeclarationADefinition()) {
179 RewriteForwardClassDecl(D);
180 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000181 } else {
182 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000183 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000184 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000185 }
186 }
187
188 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
189 if (!Proto->isThisDeclarationADefinition()) {
190 RewriteForwardProtocolDecl(D);
191 break;
192 }
193 }
194
195 HandleTopLevelSingleDecl(*I);
196 }
197 return true;
198 }
199 void HandleTopLevelSingleDecl(Decl *D);
200 void HandleDeclInMainFile(Decl *D);
201 RewriteModernObjC(std::string inFile, raw_ostream *OS,
202 DiagnosticsEngine &D, const LangOptions &LOpts,
203 bool silenceMacroWarn);
204
205 ~RewriteModernObjC() {}
206
207 virtual void HandleTranslationUnit(ASTContext &C);
208
209 void ReplaceStmt(Stmt *Old, Stmt *New) {
210 Stmt *ReplacingStmt = ReplacedNodes[Old];
211
212 if (ReplacingStmt)
213 return; // We can't rewrite the same node twice.
214
215 if (DisableReplaceStmt)
216 return;
217
218 // If replacement succeeded or warning disabled return with no warning.
219 if (!Rewrite.ReplaceStmt(Old, New)) {
220 ReplacedNodes[Old] = New;
221 return;
222 }
223 if (SilenceRewriteMacroWarning)
224 return;
225 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
226 << Old->getSourceRange();
227 }
228
229 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
230 if (DisableReplaceStmt)
231 return;
232
233 // Measure the old text.
234 int Size = Rewrite.getRangeSize(SrcRange);
235 if (Size == -1) {
236 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
237 << Old->getSourceRange();
238 return;
239 }
240 // Get the new text.
241 std::string SStr;
242 llvm::raw_string_ostream S(SStr);
243 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
244 const std::string &Str = S.str();
245
246 // If replacement succeeded or warning disabled return with no warning.
247 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
248 ReplacedNodes[Old] = New;
249 return;
250 }
251 if (SilenceRewriteMacroWarning)
252 return;
253 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
254 << Old->getSourceRange();
255 }
256
257 void InsertText(SourceLocation Loc, StringRef Str,
258 bool InsertAfter = true) {
259 // If insertion succeeded or warning disabled return with no warning.
260 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
261 SilenceRewriteMacroWarning)
262 return;
263
264 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
265 }
266
267 void ReplaceText(SourceLocation Start, unsigned OrigLength,
268 StringRef Str) {
269 // If removal succeeded or warning disabled return with no warning.
270 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
271 SilenceRewriteMacroWarning)
272 return;
273
274 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
275 }
276
277 // Syntactic Rewriting.
278 void RewriteRecordBody(RecordDecl *RD);
279 void RewriteInclude();
280 void RewriteForwardClassDecl(DeclGroupRef D);
281 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
282 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
283 const std::string &typedefString);
284 void RewriteImplementations();
285 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
286 ObjCImplementationDecl *IMD,
287 ObjCCategoryImplDecl *CID);
288 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
289 void RewriteImplementationDecl(Decl *Dcl);
290 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
291 ObjCMethodDecl *MDecl, std::string &ResultStr);
292 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
293 const FunctionType *&FPRetType);
294 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
295 ValueDecl *VD, bool def=false);
296 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
297 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
298 void RewriteForwardProtocolDecl(DeclGroupRef D);
299 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
300 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
301 void RewriteProperty(ObjCPropertyDecl *prop);
302 void RewriteFunctionDecl(FunctionDecl *FD);
303 void RewriteBlockPointerType(std::string& Str, QualType Type);
304 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
305 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
306 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
307 void RewriteTypeOfDecl(VarDecl *VD);
308 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
309
310 // Expression Rewriting.
311 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
312 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
313 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
314 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
316 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
317 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
318 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000319 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
320 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
321 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
322 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
323 SourceLocation OrigEnd);
324 Stmt *RewriteBreakStmt(BreakStmt *S);
325 Stmt *RewriteContinueStmt(ContinueStmt *S);
326 void RewriteCastExpr(CStyleCastExpr *CE);
327
328 // Block rewriting.
329 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
330
331 // Block specific rewrite rules.
332 void RewriteBlockPointerDecl(NamedDecl *VD);
333 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000334 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000335 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
336 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
337
338 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
339 std::string &Result);
340
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000341 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
342
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000343 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
344
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000345 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
346 std::string &Result);
347
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000348 virtual void Initialize(ASTContext &context);
349
350 // Misc. AST transformation routines. Somtimes they end up calling
351 // rewriting routines on the new ASTs.
352 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
353 Expr **args, unsigned nargs,
354 SourceLocation StartLoc=SourceLocation(),
355 SourceLocation EndLoc=SourceLocation());
356
357 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
358 SourceLocation StartLoc=SourceLocation(),
359 SourceLocation EndLoc=SourceLocation());
360
361 void SynthCountByEnumWithState(std::string &buf);
362 void SynthMsgSendFunctionDecl();
363 void SynthMsgSendSuperFunctionDecl();
364 void SynthMsgSendStretFunctionDecl();
365 void SynthMsgSendFpretFunctionDecl();
366 void SynthMsgSendSuperStretFunctionDecl();
367 void SynthGetClassFunctionDecl();
368 void SynthGetMetaClassFunctionDecl();
369 void SynthGetSuperClassFunctionDecl();
370 void SynthSelGetUidFunctionDecl();
371 void SynthSuperContructorFunctionDecl();
372
373 // Rewriting metadata
374 template<typename MethodIterator>
375 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
376 MethodIterator MethodEnd,
377 bool IsInstanceMethod,
378 StringRef prefix,
379 StringRef ClassName,
380 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000381 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
382 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000383 virtual void RewriteObjCProtocolListMetaData(
384 const ObjCList<ObjCProtocolDecl> &Prots,
385 StringRef prefix, StringRef ClassName, std::string &Result);
386 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
387 std::string &Result);
388 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000389 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000390 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
391 std::string &Result);
392
393 // Rewriting ivar
394 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
395 std::string &Result);
396 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
397
398
399 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
400 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
401 StringRef funcName, std::string Tag);
402 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
403 StringRef funcName, std::string Tag);
404 std::string SynthesizeBlockImpl(BlockExpr *CE,
405 std::string Tag, std::string Desc);
406 std::string SynthesizeBlockDescriptor(std::string DescTag,
407 std::string ImplTag,
408 int i, StringRef funcName,
409 unsigned hasCopy);
410 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
411 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
412 StringRef FunName);
413 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
414 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000415 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000416
417 // Misc. helper routines.
418 QualType getProtocolType();
419 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000420 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
421 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
422 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
423
424 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
425 void CollectBlockDeclRefInfo(BlockExpr *Exp);
426 void GetBlockDeclRefExprs(Stmt *S);
427 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000428 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000429 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
430
431 // We avoid calling Type::isBlockPointerType(), since it operates on the
432 // canonical type. We only care if the top-level type is a closure pointer.
433 bool isTopLevelBlockPointerType(QualType T) {
434 return isa<BlockPointerType>(T);
435 }
436
437 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
438 /// to a function pointer type and upon success, returns true; false
439 /// otherwise.
440 bool convertBlockPointerToFunctionPointer(QualType &T) {
441 if (isTopLevelBlockPointerType(T)) {
442 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
443 T = Context->getPointerType(BPT->getPointeeType());
444 return true;
445 }
446 return false;
447 }
448
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000449 bool convertObjCTypeToCStyleType(QualType &T);
450
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000451 bool needToScanForQualifiers(QualType T);
452 QualType getSuperStructType();
453 QualType getConstantStringStructType();
454 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
455 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
456
457 void convertToUnqualifiedObjCType(QualType &T) {
458 if (T->isObjCQualifiedIdType())
459 T = Context->getObjCIdType();
460 else if (T->isObjCQualifiedClassType())
461 T = Context->getObjCClassType();
462 else if (T->isObjCObjectPointerType() &&
463 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
464 if (const ObjCObjectPointerType * OBJPT =
465 T->getAsObjCInterfacePointerType()) {
466 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
467 T = QualType(IFaceT, 0);
468 T = Context->getPointerType(T);
469 }
470 }
471 }
472
473 // FIXME: This predicate seems like it would be useful to add to ASTContext.
474 bool isObjCType(QualType T) {
475 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
476 return false;
477
478 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
479
480 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
481 OCT == Context->getCanonicalType(Context->getObjCClassType()))
482 return true;
483
484 if (const PointerType *PT = OCT->getAs<PointerType>()) {
485 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
486 PT->getPointeeType()->isObjCQualifiedIdType())
487 return true;
488 }
489 return false;
490 }
491 bool PointerTypeTakesAnyBlockArguments(QualType QT);
492 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
493 void GetExtentOfArgList(const char *Name, const char *&LParen,
494 const char *&RParen);
495
496 void QuoteDoublequotes(std::string &From, std::string &To) {
497 for (unsigned i = 0; i < From.length(); i++) {
498 if (From[i] == '"')
499 To += "\\\"";
500 else
501 To += From[i];
502 }
503 }
504
505 QualType getSimpleFunctionType(QualType result,
506 const QualType *args,
507 unsigned numArgs,
508 bool variadic = false) {
509 if (result == Context->getObjCInstanceType())
510 result = Context->getObjCIdType();
511 FunctionProtoType::ExtProtoInfo fpi;
512 fpi.Variadic = variadic;
513 return Context->getFunctionType(result, args, numArgs, fpi);
514 }
515
516 // Helper function: create a CStyleCastExpr with trivial type source info.
517 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
518 CastKind Kind, Expr *E) {
519 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
520 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
521 SourceLocation(), SourceLocation());
522 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000523
524 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
525 IdentifierInfo* II = &Context->Idents.get("load");
526 Selector LoadSel = Context->Selectors.getSelector(0, &II);
527 return OD->getClassMethod(LoadSel) != 0;
528 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000529 };
530
531}
532
533void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
534 NamedDecl *D) {
535 if (const FunctionProtoType *fproto
536 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
537 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
538 E = fproto->arg_type_end(); I && (I != E); ++I)
539 if (isTopLevelBlockPointerType(*I)) {
540 // All the args are checked/rewritten. Don't call twice!
541 RewriteBlockPointerDecl(D);
542 break;
543 }
544 }
545}
546
547void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
548 const PointerType *PT = funcType->getAs<PointerType>();
549 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
550 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
551}
552
553static bool IsHeaderFile(const std::string &Filename) {
554 std::string::size_type DotPos = Filename.rfind('.');
555
556 if (DotPos == std::string::npos) {
557 // no file extension
558 return false;
559 }
560
561 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
562 // C header: .h
563 // C++ header: .hh or .H;
564 return Ext == "h" || Ext == "hh" || Ext == "H";
565}
566
567RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
568 DiagnosticsEngine &D, const LangOptions &LOpts,
569 bool silenceMacroWarn)
570 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
571 SilenceRewriteMacroWarning(silenceMacroWarn) {
572 IsHeader = IsHeaderFile(inFile);
573 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
574 "rewriting sub-expression within a macro (may not be correct)");
575 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
576 DiagnosticsEngine::Warning,
577 "rewriter doesn't support user-specified control flow semantics "
578 "for @try/@finally (code may not execute properly)");
579}
580
581ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
582 raw_ostream* OS,
583 DiagnosticsEngine &Diags,
584 const LangOptions &LOpts,
585 bool SilenceRewriteMacroWarning) {
586 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
587}
588
589void RewriteModernObjC::InitializeCommon(ASTContext &context) {
590 Context = &context;
591 SM = &Context->getSourceManager();
592 TUDecl = Context->getTranslationUnitDecl();
593 MsgSendFunctionDecl = 0;
594 MsgSendSuperFunctionDecl = 0;
595 MsgSendStretFunctionDecl = 0;
596 MsgSendSuperStretFunctionDecl = 0;
597 MsgSendFpretFunctionDecl = 0;
598 GetClassFunctionDecl = 0;
599 GetMetaClassFunctionDecl = 0;
600 GetSuperClassFunctionDecl = 0;
601 SelGetUidFunctionDecl = 0;
602 CFStringFunctionDecl = 0;
603 ConstantStringClassReference = 0;
604 NSStringRecord = 0;
605 CurMethodDef = 0;
606 CurFunctionDef = 0;
607 CurFunctionDeclToDeclareForBlock = 0;
608 GlobalVarDecl = 0;
609 SuperStructDecl = 0;
610 ProtocolTypeDecl = 0;
611 ConstantStringDecl = 0;
612 BcLabelCount = 0;
613 SuperContructorFunctionDecl = 0;
614 NumObjCStringLiterals = 0;
615 PropParentMap = 0;
616 CurrentBody = 0;
617 DisableReplaceStmt = false;
618 objc_impl_method = false;
619
620 // Get the ID and start/end of the main file.
621 MainFileID = SM->getMainFileID();
622 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
623 MainFileStart = MainBuf->getBufferStart();
624 MainFileEnd = MainBuf->getBufferEnd();
625
David Blaikie4e4d0842012-03-11 07:00:24 +0000626 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000627}
628
629//===----------------------------------------------------------------------===//
630// Top Level Driver Code
631//===----------------------------------------------------------------------===//
632
633void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
634 if (Diags.hasErrorOccurred())
635 return;
636
637 // Two cases: either the decl could be in the main file, or it could be in a
638 // #included file. If the former, rewrite it now. If the later, check to see
639 // if we rewrote the #include/#import.
640 SourceLocation Loc = D->getLocation();
641 Loc = SM->getExpansionLoc(Loc);
642
643 // If this is for a builtin, ignore it.
644 if (Loc.isInvalid()) return;
645
646 // Look for built-in declarations that we need to refer during the rewrite.
647 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
648 RewriteFunctionDecl(FD);
649 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
650 // declared in <Foundation/NSString.h>
651 if (FVD->getName() == "_NSConstantStringClassReference") {
652 ConstantStringClassReference = FVD;
653 return;
654 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000655 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
656 RewriteCategoryDecl(CD);
657 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
658 if (PD->isThisDeclarationADefinition())
659 RewriteProtocolDecl(PD);
660 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
661 // Recurse into linkage specifications
662 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
663 DIEnd = LSD->decls_end();
664 DI != DIEnd; ) {
665 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
666 if (!IFace->isThisDeclarationADefinition()) {
667 SmallVector<Decl *, 8> DG;
668 SourceLocation StartLoc = IFace->getLocStart();
669 do {
670 if (isa<ObjCInterfaceDecl>(*DI) &&
671 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
672 StartLoc == (*DI)->getLocStart())
673 DG.push_back(*DI);
674 else
675 break;
676
677 ++DI;
678 } while (DI != DIEnd);
679 RewriteForwardClassDecl(DG);
680 continue;
681 }
682 }
683
684 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
685 if (!Proto->isThisDeclarationADefinition()) {
686 SmallVector<Decl *, 8> DG;
687 SourceLocation StartLoc = Proto->getLocStart();
688 do {
689 if (isa<ObjCProtocolDecl>(*DI) &&
690 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
691 StartLoc == (*DI)->getLocStart())
692 DG.push_back(*DI);
693 else
694 break;
695
696 ++DI;
697 } while (DI != DIEnd);
698 RewriteForwardProtocolDecl(DG);
699 continue;
700 }
701 }
702
703 HandleTopLevelSingleDecl(*DI);
704 ++DI;
705 }
706 }
707 // If we have a decl in the main file, see if we should rewrite it.
708 if (SM->isFromMainFile(Loc))
709 return HandleDeclInMainFile(D);
710}
711
712//===----------------------------------------------------------------------===//
713// Syntactic (non-AST) Rewriting Code
714//===----------------------------------------------------------------------===//
715
716void RewriteModernObjC::RewriteInclude() {
717 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
718 StringRef MainBuf = SM->getBufferData(MainFileID);
719 const char *MainBufStart = MainBuf.begin();
720 const char *MainBufEnd = MainBuf.end();
721 size_t ImportLen = strlen("import");
722
723 // Loop over the whole file, looking for includes.
724 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
725 if (*BufPtr == '#') {
726 if (++BufPtr == MainBufEnd)
727 return;
728 while (*BufPtr == ' ' || *BufPtr == '\t')
729 if (++BufPtr == MainBufEnd)
730 return;
731 if (!strncmp(BufPtr, "import", ImportLen)) {
732 // replace import with include
733 SourceLocation ImportLoc =
734 LocStart.getLocWithOffset(BufPtr-MainBufStart);
735 ReplaceText(ImportLoc, ImportLen, "include");
736 BufPtr += ImportLen;
737 }
738 }
739 }
740}
741
742static std::string getIvarAccessString(ObjCIvarDecl *OID) {
743 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
744 std::string S;
745 S = "((struct ";
746 S += ClassDecl->getIdentifier()->getName();
747 S += "_IMPL *)self)->";
748 S += OID->getName();
749 return S;
750}
751
752void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
753 ObjCImplementationDecl *IMD,
754 ObjCCategoryImplDecl *CID) {
755 static bool objcGetPropertyDefined = false;
756 static bool objcSetPropertyDefined = false;
757 SourceLocation startLoc = PID->getLocStart();
758 InsertText(startLoc, "// ");
759 const char *startBuf = SM->getCharacterData(startLoc);
760 assert((*startBuf == '@') && "bogus @synthesize location");
761 const char *semiBuf = strchr(startBuf, ';');
762 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
763 SourceLocation onePastSemiLoc =
764 startLoc.getLocWithOffset(semiBuf-startBuf+1);
765
766 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
767 return; // FIXME: is this correct?
768
769 // Generate the 'getter' function.
770 ObjCPropertyDecl *PD = PID->getPropertyDecl();
771 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
772
773 if (!OID)
774 return;
775 unsigned Attributes = PD->getPropertyAttributes();
776 if (!PD->getGetterMethodDecl()->isDefined()) {
777 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
778 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
779 ObjCPropertyDecl::OBJC_PR_copy));
780 std::string Getr;
781 if (GenGetProperty && !objcGetPropertyDefined) {
782 objcGetPropertyDefined = true;
783 // FIXME. Is this attribute correct in all cases?
784 Getr = "\nextern \"C\" __declspec(dllimport) "
785 "id objc_getProperty(id, SEL, long, bool);\n";
786 }
787 RewriteObjCMethodDecl(OID->getContainingInterface(),
788 PD->getGetterMethodDecl(), Getr);
789 Getr += "{ ";
790 // Synthesize an explicit cast to gain access to the ivar.
791 // See objc-act.c:objc_synthesize_new_getter() for details.
792 if (GenGetProperty) {
793 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
794 Getr += "typedef ";
795 const FunctionType *FPRetType = 0;
796 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
797 FPRetType);
798 Getr += " _TYPE";
799 if (FPRetType) {
800 Getr += ")"; // close the precedence "scope" for "*".
801
802 // Now, emit the argument types (if any).
803 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
804 Getr += "(";
805 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
806 if (i) Getr += ", ";
807 std::string ParamStr = FT->getArgType(i).getAsString(
808 Context->getPrintingPolicy());
809 Getr += ParamStr;
810 }
811 if (FT->isVariadic()) {
812 if (FT->getNumArgs()) Getr += ", ";
813 Getr += "...";
814 }
815 Getr += ")";
816 } else
817 Getr += "()";
818 }
819 Getr += ";\n";
820 Getr += "return (_TYPE)";
821 Getr += "objc_getProperty(self, _cmd, ";
822 RewriteIvarOffsetComputation(OID, Getr);
823 Getr += ", 1)";
824 }
825 else
826 Getr += "return " + getIvarAccessString(OID);
827 Getr += "; }";
828 InsertText(onePastSemiLoc, Getr);
829 }
830
831 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
832 return;
833
834 // Generate the 'setter' function.
835 std::string Setr;
836 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
837 ObjCPropertyDecl::OBJC_PR_copy);
838 if (GenSetProperty && !objcSetPropertyDefined) {
839 objcSetPropertyDefined = true;
840 // FIXME. Is this attribute correct in all cases?
841 Setr = "\nextern \"C\" __declspec(dllimport) "
842 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
843 }
844
845 RewriteObjCMethodDecl(OID->getContainingInterface(),
846 PD->getSetterMethodDecl(), Setr);
847 Setr += "{ ";
848 // Synthesize an explicit cast to initialize the ivar.
849 // See objc-act.c:objc_synthesize_new_setter() for details.
850 if (GenSetProperty) {
851 Setr += "objc_setProperty (self, _cmd, ";
852 RewriteIvarOffsetComputation(OID, Setr);
853 Setr += ", (id)";
854 Setr += PD->getName();
855 Setr += ", ";
856 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
857 Setr += "0, ";
858 else
859 Setr += "1, ";
860 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
861 Setr += "1)";
862 else
863 Setr += "0)";
864 }
865 else {
866 Setr += getIvarAccessString(OID) + " = ";
867 Setr += PD->getName();
868 }
869 Setr += "; }";
870 InsertText(onePastSemiLoc, Setr);
871}
872
873static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
874 std::string &typedefString) {
875 typedefString += "#ifndef _REWRITER_typedef_";
876 typedefString += ForwardDecl->getNameAsString();
877 typedefString += "\n";
878 typedefString += "#define _REWRITER_typedef_";
879 typedefString += ForwardDecl->getNameAsString();
880 typedefString += "\n";
881 typedefString += "typedef struct objc_object ";
882 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000883 // typedef struct { } _objc_exc_Classname;
884 typedefString += ";\ntypedef struct {} _objc_exc_";
885 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000886 typedefString += ";\n#endif\n";
887}
888
889void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
890 const std::string &typedefString) {
891 SourceLocation startLoc = ClassDecl->getLocStart();
892 const char *startBuf = SM->getCharacterData(startLoc);
893 const char *semiPtr = strchr(startBuf, ';');
894 // Replace the @class with typedefs corresponding to the classes.
895 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
896}
897
898void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
899 std::string typedefString;
900 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
901 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
902 if (I == D.begin()) {
903 // Translate to typedef's that forward reference structs with the same name
904 // as the class. As a convenience, we include the original declaration
905 // as a comment.
906 typedefString += "// @class ";
907 typedefString += ForwardDecl->getNameAsString();
908 typedefString += ";\n";
909 }
910 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
911 }
912 DeclGroupRef::iterator I = D.begin();
913 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
914}
915
916void RewriteModernObjC::RewriteForwardClassDecl(
917 const llvm::SmallVector<Decl*, 8> &D) {
918 std::string typedefString;
919 for (unsigned i = 0; i < D.size(); i++) {
920 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
921 if (i == 0) {
922 typedefString += "// @class ";
923 typedefString += ForwardDecl->getNameAsString();
924 typedefString += ";\n";
925 }
926 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
927 }
928 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
929}
930
931void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
932 // When method is a synthesized one, such as a getter/setter there is
933 // nothing to rewrite.
934 if (Method->isImplicit())
935 return;
936 SourceLocation LocStart = Method->getLocStart();
937 SourceLocation LocEnd = Method->getLocEnd();
938
939 if (SM->getExpansionLineNumber(LocEnd) >
940 SM->getExpansionLineNumber(LocStart)) {
941 InsertText(LocStart, "#if 0\n");
942 ReplaceText(LocEnd, 1, ";\n#endif\n");
943 } else {
944 InsertText(LocStart, "// ");
945 }
946}
947
948void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
949 SourceLocation Loc = prop->getAtLoc();
950
951 ReplaceText(Loc, 0, "// ");
952 // FIXME: handle properties that are declared across multiple lines.
953}
954
955void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
956 SourceLocation LocStart = CatDecl->getLocStart();
957
958 // FIXME: handle category headers that are declared across multiple lines.
959 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000960 if (CatDecl->getIvarLBraceLoc().isValid())
961 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000962 for (ObjCCategoryDecl::ivar_iterator
963 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
964 ObjCIvarDecl *Ivar = (*I);
965 SourceLocation LocStart = Ivar->getLocStart();
966 ReplaceText(LocStart, 0, "// ");
967 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000968 if (CatDecl->getIvarRBraceLoc().isValid())
969 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
970
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000971 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
972 E = CatDecl->prop_end(); I != E; ++I)
973 RewriteProperty(*I);
974
975 for (ObjCCategoryDecl::instmeth_iterator
976 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
977 I != E; ++I)
978 RewriteMethodDeclaration(*I);
979 for (ObjCCategoryDecl::classmeth_iterator
980 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
981 I != E; ++I)
982 RewriteMethodDeclaration(*I);
983
984 // Lastly, comment out the @end.
985 ReplaceText(CatDecl->getAtEndRange().getBegin(),
986 strlen("@end"), "/* @end */");
987}
988
989void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
990 SourceLocation LocStart = PDecl->getLocStart();
991 assert(PDecl->isThisDeclarationADefinition());
992
993 // FIXME: handle protocol headers that are declared across multiple lines.
994 ReplaceText(LocStart, 0, "// ");
995
996 for (ObjCProtocolDecl::instmeth_iterator
997 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
998 I != E; ++I)
999 RewriteMethodDeclaration(*I);
1000 for (ObjCProtocolDecl::classmeth_iterator
1001 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1002 I != E; ++I)
1003 RewriteMethodDeclaration(*I);
1004
1005 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1006 E = PDecl->prop_end(); I != E; ++I)
1007 RewriteProperty(*I);
1008
1009 // Lastly, comment out the @end.
1010 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1011 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1012
1013 // Must comment out @optional/@required
1014 const char *startBuf = SM->getCharacterData(LocStart);
1015 const char *endBuf = SM->getCharacterData(LocEnd);
1016 for (const char *p = startBuf; p < endBuf; p++) {
1017 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1018 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1019 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1020
1021 }
1022 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1023 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1024 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1025
1026 }
1027 }
1028}
1029
1030void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1031 SourceLocation LocStart = (*D.begin())->getLocStart();
1032 if (LocStart.isInvalid())
1033 llvm_unreachable("Invalid SourceLocation");
1034 // FIXME: handle forward protocol that are declared across multiple lines.
1035 ReplaceText(LocStart, 0, "// ");
1036}
1037
1038void
1039RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1040 SourceLocation LocStart = DG[0]->getLocStart();
1041 if (LocStart.isInvalid())
1042 llvm_unreachable("Invalid SourceLocation");
1043 // FIXME: handle forward protocol that are declared across multiple lines.
1044 ReplaceText(LocStart, 0, "// ");
1045}
1046
1047void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1048 const FunctionType *&FPRetType) {
1049 if (T->isObjCQualifiedIdType())
1050 ResultStr += "id";
1051 else if (T->isFunctionPointerType() ||
1052 T->isBlockPointerType()) {
1053 // needs special handling, since pointer-to-functions have special
1054 // syntax (where a decaration models use).
1055 QualType retType = T;
1056 QualType PointeeTy;
1057 if (const PointerType* PT = retType->getAs<PointerType>())
1058 PointeeTy = PT->getPointeeType();
1059 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1060 PointeeTy = BPT->getPointeeType();
1061 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1062 ResultStr += FPRetType->getResultType().getAsString(
1063 Context->getPrintingPolicy());
1064 ResultStr += "(*";
1065 }
1066 } else
1067 ResultStr += T.getAsString(Context->getPrintingPolicy());
1068}
1069
1070void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1071 ObjCMethodDecl *OMD,
1072 std::string &ResultStr) {
1073 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1074 const FunctionType *FPRetType = 0;
1075 ResultStr += "\nstatic ";
1076 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1077 ResultStr += " ";
1078
1079 // Unique method name
1080 std::string NameStr;
1081
1082 if (OMD->isInstanceMethod())
1083 NameStr += "_I_";
1084 else
1085 NameStr += "_C_";
1086
1087 NameStr += IDecl->getNameAsString();
1088 NameStr += "_";
1089
1090 if (ObjCCategoryImplDecl *CID =
1091 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1092 NameStr += CID->getNameAsString();
1093 NameStr += "_";
1094 }
1095 // Append selector names, replacing ':' with '_'
1096 {
1097 std::string selString = OMD->getSelector().getAsString();
1098 int len = selString.size();
1099 for (int i = 0; i < len; i++)
1100 if (selString[i] == ':')
1101 selString[i] = '_';
1102 NameStr += selString;
1103 }
1104 // Remember this name for metadata emission
1105 MethodInternalNames[OMD] = NameStr;
1106 ResultStr += NameStr;
1107
1108 // Rewrite arguments
1109 ResultStr += "(";
1110
1111 // invisible arguments
1112 if (OMD->isInstanceMethod()) {
1113 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1114 selfTy = Context->getPointerType(selfTy);
1115 if (!LangOpts.MicrosoftExt) {
1116 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1117 ResultStr += "struct ";
1118 }
1119 // When rewriting for Microsoft, explicitly omit the structure name.
1120 ResultStr += IDecl->getNameAsString();
1121 ResultStr += " *";
1122 }
1123 else
1124 ResultStr += Context->getObjCClassType().getAsString(
1125 Context->getPrintingPolicy());
1126
1127 ResultStr += " self, ";
1128 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1129 ResultStr += " _cmd";
1130
1131 // Method arguments.
1132 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1133 E = OMD->param_end(); PI != E; ++PI) {
1134 ParmVarDecl *PDecl = *PI;
1135 ResultStr += ", ";
1136 if (PDecl->getType()->isObjCQualifiedIdType()) {
1137 ResultStr += "id ";
1138 ResultStr += PDecl->getNameAsString();
1139 } else {
1140 std::string Name = PDecl->getNameAsString();
1141 QualType QT = PDecl->getType();
1142 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1143 if (convertBlockPointerToFunctionPointer(QT))
1144 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1145 else
1146 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1147 ResultStr += Name;
1148 }
1149 }
1150 if (OMD->isVariadic())
1151 ResultStr += ", ...";
1152 ResultStr += ") ";
1153
1154 if (FPRetType) {
1155 ResultStr += ")"; // close the precedence "scope" for "*".
1156
1157 // Now, emit the argument types (if any).
1158 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1159 ResultStr += "(";
1160 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1161 if (i) ResultStr += ", ";
1162 std::string ParamStr = FT->getArgType(i).getAsString(
1163 Context->getPrintingPolicy());
1164 ResultStr += ParamStr;
1165 }
1166 if (FT->isVariadic()) {
1167 if (FT->getNumArgs()) ResultStr += ", ";
1168 ResultStr += "...";
1169 }
1170 ResultStr += ")";
1171 } else {
1172 ResultStr += "()";
1173 }
1174 }
1175}
1176void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1177 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1178 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1179
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001180 if (IMD) {
1181 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001182 if (IMD->getIvarLBraceLoc().isValid())
1183 InsertText(IMD->getIvarLBraceLoc(), "// ");
1184 for (ObjCImplementationDecl::ivar_iterator
1185 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1186 ObjCIvarDecl *Ivar = (*I);
1187 SourceLocation LocStart = Ivar->getLocStart();
1188 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001189 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001190 if (IMD->getIvarRBraceLoc().isValid())
1191 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001192 }
1193 else
1194 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001195
1196 for (ObjCCategoryImplDecl::instmeth_iterator
1197 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1198 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1199 I != E; ++I) {
1200 std::string ResultStr;
1201 ObjCMethodDecl *OMD = *I;
1202 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1203 SourceLocation LocStart = OMD->getLocStart();
1204 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1205
1206 const char *startBuf = SM->getCharacterData(LocStart);
1207 const char *endBuf = SM->getCharacterData(LocEnd);
1208 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1209 }
1210
1211 for (ObjCCategoryImplDecl::classmeth_iterator
1212 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1213 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1214 I != E; ++I) {
1215 std::string ResultStr;
1216 ObjCMethodDecl *OMD = *I;
1217 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1218 SourceLocation LocStart = OMD->getLocStart();
1219 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1220
1221 const char *startBuf = SM->getCharacterData(LocStart);
1222 const char *endBuf = SM->getCharacterData(LocEnd);
1223 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1224 }
1225 for (ObjCCategoryImplDecl::propimpl_iterator
1226 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1227 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1228 I != E; ++I) {
1229 RewritePropertyImplDecl(*I, IMD, CID);
1230 }
1231
1232 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1233}
1234
1235void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001236 // Do not synthesize more than once.
1237 if (ObjCSynthesizedStructs.count(ClassDecl))
1238 return;
1239 // Make sure super class's are written before current class is written.
1240 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1241 while (SuperClass) {
1242 RewriteInterfaceDecl(SuperClass);
1243 SuperClass = SuperClass->getSuperClass();
1244 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001245 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001246 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001247 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001248 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001249 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1250
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001251 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001252 // Mark this typedef as having been written into its c++ equivalent.
1253 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001254
1255 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001256 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001257 RewriteProperty(*I);
1258 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001259 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001260 I != E; ++I)
1261 RewriteMethodDeclaration(*I);
1262 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001263 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001264 I != E; ++I)
1265 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001266
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001267 // Lastly, comment out the @end.
1268 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1269 "/* @end */");
1270 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001271}
1272
1273Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1274 SourceRange OldRange = PseudoOp->getSourceRange();
1275
1276 // We just magically know some things about the structure of this
1277 // expression.
1278 ObjCMessageExpr *OldMsg =
1279 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1280 PseudoOp->getNumSemanticExprs() - 1));
1281
1282 // Because the rewriter doesn't allow us to rewrite rewritten code,
1283 // we need to suppress rewriting the sub-statements.
1284 Expr *Base, *RHS;
1285 {
1286 DisableReplaceStmtScope S(*this);
1287
1288 // Rebuild the base expression if we have one.
1289 Base = 0;
1290 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1291 Base = OldMsg->getInstanceReceiver();
1292 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1293 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1294 }
1295
1296 // Rebuild the RHS.
1297 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1298 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1299 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1300 }
1301
1302 // TODO: avoid this copy.
1303 SmallVector<SourceLocation, 1> SelLocs;
1304 OldMsg->getSelectorLocs(SelLocs);
1305
1306 ObjCMessageExpr *NewMsg = 0;
1307 switch (OldMsg->getReceiverKind()) {
1308 case ObjCMessageExpr::Class:
1309 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1310 OldMsg->getValueKind(),
1311 OldMsg->getLeftLoc(),
1312 OldMsg->getClassReceiverTypeInfo(),
1313 OldMsg->getSelector(),
1314 SelLocs,
1315 OldMsg->getMethodDecl(),
1316 RHS,
1317 OldMsg->getRightLoc(),
1318 OldMsg->isImplicit());
1319 break;
1320
1321 case ObjCMessageExpr::Instance:
1322 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1323 OldMsg->getValueKind(),
1324 OldMsg->getLeftLoc(),
1325 Base,
1326 OldMsg->getSelector(),
1327 SelLocs,
1328 OldMsg->getMethodDecl(),
1329 RHS,
1330 OldMsg->getRightLoc(),
1331 OldMsg->isImplicit());
1332 break;
1333
1334 case ObjCMessageExpr::SuperClass:
1335 case ObjCMessageExpr::SuperInstance:
1336 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1337 OldMsg->getValueKind(),
1338 OldMsg->getLeftLoc(),
1339 OldMsg->getSuperLoc(),
1340 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1341 OldMsg->getSuperType(),
1342 OldMsg->getSelector(),
1343 SelLocs,
1344 OldMsg->getMethodDecl(),
1345 RHS,
1346 OldMsg->getRightLoc(),
1347 OldMsg->isImplicit());
1348 break;
1349 }
1350
1351 Stmt *Replacement = SynthMessageExpr(NewMsg);
1352 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1353 return Replacement;
1354}
1355
1356Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1357 SourceRange OldRange = PseudoOp->getSourceRange();
1358
1359 // We just magically know some things about the structure of this
1360 // expression.
1361 ObjCMessageExpr *OldMsg =
1362 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1363
1364 // Because the rewriter doesn't allow us to rewrite rewritten code,
1365 // we need to suppress rewriting the sub-statements.
1366 Expr *Base = 0;
1367 {
1368 DisableReplaceStmtScope S(*this);
1369
1370 // Rebuild the base expression if we have one.
1371 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1372 Base = OldMsg->getInstanceReceiver();
1373 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1374 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1375 }
1376 }
1377
1378 // Intentionally empty.
1379 SmallVector<SourceLocation, 1> SelLocs;
1380 SmallVector<Expr*, 1> Args;
1381
1382 ObjCMessageExpr *NewMsg = 0;
1383 switch (OldMsg->getReceiverKind()) {
1384 case ObjCMessageExpr::Class:
1385 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1386 OldMsg->getValueKind(),
1387 OldMsg->getLeftLoc(),
1388 OldMsg->getClassReceiverTypeInfo(),
1389 OldMsg->getSelector(),
1390 SelLocs,
1391 OldMsg->getMethodDecl(),
1392 Args,
1393 OldMsg->getRightLoc(),
1394 OldMsg->isImplicit());
1395 break;
1396
1397 case ObjCMessageExpr::Instance:
1398 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1399 OldMsg->getValueKind(),
1400 OldMsg->getLeftLoc(),
1401 Base,
1402 OldMsg->getSelector(),
1403 SelLocs,
1404 OldMsg->getMethodDecl(),
1405 Args,
1406 OldMsg->getRightLoc(),
1407 OldMsg->isImplicit());
1408 break;
1409
1410 case ObjCMessageExpr::SuperClass:
1411 case ObjCMessageExpr::SuperInstance:
1412 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1413 OldMsg->getValueKind(),
1414 OldMsg->getLeftLoc(),
1415 OldMsg->getSuperLoc(),
1416 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1417 OldMsg->getSuperType(),
1418 OldMsg->getSelector(),
1419 SelLocs,
1420 OldMsg->getMethodDecl(),
1421 Args,
1422 OldMsg->getRightLoc(),
1423 OldMsg->isImplicit());
1424 break;
1425 }
1426
1427 Stmt *Replacement = SynthMessageExpr(NewMsg);
1428 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1429 return Replacement;
1430}
1431
1432/// SynthCountByEnumWithState - To print:
1433/// ((unsigned int (*)
1434/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1435/// (void *)objc_msgSend)((id)l_collection,
1436/// sel_registerName(
1437/// "countByEnumeratingWithState:objects:count:"),
1438/// &enumState,
1439/// (id *)__rw_items, (unsigned int)16)
1440///
1441void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1442 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1443 "id *, unsigned int))(void *)objc_msgSend)";
1444 buf += "\n\t\t";
1445 buf += "((id)l_collection,\n\t\t";
1446 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1447 buf += "\n\t\t";
1448 buf += "&enumState, "
1449 "(id *)__rw_items, (unsigned int)16)";
1450}
1451
1452/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1453/// statement to exit to its outer synthesized loop.
1454///
1455Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1456 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1457 return S;
1458 // replace break with goto __break_label
1459 std::string buf;
1460
1461 SourceLocation startLoc = S->getLocStart();
1462 buf = "goto __break_label_";
1463 buf += utostr(ObjCBcLabelNo.back());
1464 ReplaceText(startLoc, strlen("break"), buf);
1465
1466 return 0;
1467}
1468
1469/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1470/// statement to continue with its inner synthesized loop.
1471///
1472Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1473 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1474 return S;
1475 // replace continue with goto __continue_label
1476 std::string buf;
1477
1478 SourceLocation startLoc = S->getLocStart();
1479 buf = "goto __continue_label_";
1480 buf += utostr(ObjCBcLabelNo.back());
1481 ReplaceText(startLoc, strlen("continue"), buf);
1482
1483 return 0;
1484}
1485
1486/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1487/// It rewrites:
1488/// for ( type elem in collection) { stmts; }
1489
1490/// Into:
1491/// {
1492/// type elem;
1493/// struct __objcFastEnumerationState enumState = { 0 };
1494/// id __rw_items[16];
1495/// id l_collection = (id)collection;
1496/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1497/// objects:__rw_items count:16];
1498/// if (limit) {
1499/// unsigned long startMutations = *enumState.mutationsPtr;
1500/// do {
1501/// unsigned long counter = 0;
1502/// do {
1503/// if (startMutations != *enumState.mutationsPtr)
1504/// objc_enumerationMutation(l_collection);
1505/// elem = (type)enumState.itemsPtr[counter++];
1506/// stmts;
1507/// __continue_label: ;
1508/// } while (counter < limit);
1509/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1510/// objects:__rw_items count:16]);
1511/// elem = nil;
1512/// __break_label: ;
1513/// }
1514/// else
1515/// elem = nil;
1516/// }
1517///
1518Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1519 SourceLocation OrigEnd) {
1520 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1521 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1522 "ObjCForCollectionStmt Statement stack mismatch");
1523 assert(!ObjCBcLabelNo.empty() &&
1524 "ObjCForCollectionStmt - Label No stack empty");
1525
1526 SourceLocation startLoc = S->getLocStart();
1527 const char *startBuf = SM->getCharacterData(startLoc);
1528 StringRef elementName;
1529 std::string elementTypeAsString;
1530 std::string buf;
1531 buf = "\n{\n\t";
1532 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1533 // type elem;
1534 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1535 QualType ElementType = cast<ValueDecl>(D)->getType();
1536 if (ElementType->isObjCQualifiedIdType() ||
1537 ElementType->isObjCQualifiedInterfaceType())
1538 // Simply use 'id' for all qualified types.
1539 elementTypeAsString = "id";
1540 else
1541 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1542 buf += elementTypeAsString;
1543 buf += " ";
1544 elementName = D->getName();
1545 buf += elementName;
1546 buf += ";\n\t";
1547 }
1548 else {
1549 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1550 elementName = DR->getDecl()->getName();
1551 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1552 if (VD->getType()->isObjCQualifiedIdType() ||
1553 VD->getType()->isObjCQualifiedInterfaceType())
1554 // Simply use 'id' for all qualified types.
1555 elementTypeAsString = "id";
1556 else
1557 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1558 }
1559
1560 // struct __objcFastEnumerationState enumState = { 0 };
1561 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1562 // id __rw_items[16];
1563 buf += "id __rw_items[16];\n\t";
1564 // id l_collection = (id)
1565 buf += "id l_collection = (id)";
1566 // Find start location of 'collection' the hard way!
1567 const char *startCollectionBuf = startBuf;
1568 startCollectionBuf += 3; // skip 'for'
1569 startCollectionBuf = strchr(startCollectionBuf, '(');
1570 startCollectionBuf++; // skip '('
1571 // find 'in' and skip it.
1572 while (*startCollectionBuf != ' ' ||
1573 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1574 (*(startCollectionBuf+3) != ' ' &&
1575 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1576 startCollectionBuf++;
1577 startCollectionBuf += 3;
1578
1579 // Replace: "for (type element in" with string constructed thus far.
1580 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1581 // Replace ')' in for '(' type elem in collection ')' with ';'
1582 SourceLocation rightParenLoc = S->getRParenLoc();
1583 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1584 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1585 buf = ";\n\t";
1586
1587 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1588 // objects:__rw_items count:16];
1589 // which is synthesized into:
1590 // unsigned int limit =
1591 // ((unsigned int (*)
1592 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1593 // (void *)objc_msgSend)((id)l_collection,
1594 // sel_registerName(
1595 // "countByEnumeratingWithState:objects:count:"),
1596 // (struct __objcFastEnumerationState *)&state,
1597 // (id *)__rw_items, (unsigned int)16);
1598 buf += "unsigned long limit =\n\t\t";
1599 SynthCountByEnumWithState(buf);
1600 buf += ";\n\t";
1601 /// if (limit) {
1602 /// unsigned long startMutations = *enumState.mutationsPtr;
1603 /// do {
1604 /// unsigned long counter = 0;
1605 /// do {
1606 /// if (startMutations != *enumState.mutationsPtr)
1607 /// objc_enumerationMutation(l_collection);
1608 /// elem = (type)enumState.itemsPtr[counter++];
1609 buf += "if (limit) {\n\t";
1610 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1611 buf += "do {\n\t\t";
1612 buf += "unsigned long counter = 0;\n\t\t";
1613 buf += "do {\n\t\t\t";
1614 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1615 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1616 buf += elementName;
1617 buf += " = (";
1618 buf += elementTypeAsString;
1619 buf += ")enumState.itemsPtr[counter++];";
1620 // Replace ')' in for '(' type elem in collection ')' with all of these.
1621 ReplaceText(lparenLoc, 1, buf);
1622
1623 /// __continue_label: ;
1624 /// } while (counter < limit);
1625 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1626 /// objects:__rw_items count:16]);
1627 /// elem = nil;
1628 /// __break_label: ;
1629 /// }
1630 /// else
1631 /// elem = nil;
1632 /// }
1633 ///
1634 buf = ";\n\t";
1635 buf += "__continue_label_";
1636 buf += utostr(ObjCBcLabelNo.back());
1637 buf += ": ;";
1638 buf += "\n\t\t";
1639 buf += "} while (counter < limit);\n\t";
1640 buf += "} while (limit = ";
1641 SynthCountByEnumWithState(buf);
1642 buf += ");\n\t";
1643 buf += elementName;
1644 buf += " = ((";
1645 buf += elementTypeAsString;
1646 buf += ")0);\n\t";
1647 buf += "__break_label_";
1648 buf += utostr(ObjCBcLabelNo.back());
1649 buf += ": ;\n\t";
1650 buf += "}\n\t";
1651 buf += "else\n\t\t";
1652 buf += elementName;
1653 buf += " = ((";
1654 buf += elementTypeAsString;
1655 buf += ")0);\n\t";
1656 buf += "}\n";
1657
1658 // Insert all these *after* the statement body.
1659 // FIXME: If this should support Obj-C++, support CXXTryStmt
1660 if (isa<CompoundStmt>(S->getBody())) {
1661 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1662 InsertText(endBodyLoc, buf);
1663 } else {
1664 /* Need to treat single statements specially. For example:
1665 *
1666 * for (A *a in b) if (stuff()) break;
1667 * for (A *a in b) xxxyy;
1668 *
1669 * The following code simply scans ahead to the semi to find the actual end.
1670 */
1671 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1672 const char *semiBuf = strchr(stmtBuf, ';');
1673 assert(semiBuf && "Can't find ';'");
1674 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1675 InsertText(endBodyLoc, buf);
1676 }
1677 Stmts.pop_back();
1678 ObjCBcLabelNo.pop_back();
1679 return 0;
1680}
1681
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001682static void Write_RethrowObject(std::string &buf) {
1683 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1684 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1685 buf += "\tid rethrow;\n";
1686 buf += "\t} _fin_force_rethow(_rethrow);";
1687}
1688
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001689/// RewriteObjCSynchronizedStmt -
1690/// This routine rewrites @synchronized(expr) stmt;
1691/// into:
1692/// objc_sync_enter(expr);
1693/// @try stmt @finally { objc_sync_exit(expr); }
1694///
1695Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1696 // Get the start location and compute the semi location.
1697 SourceLocation startLoc = S->getLocStart();
1698 const char *startBuf = SM->getCharacterData(startLoc);
1699
1700 assert((*startBuf == '@') && "bogus @synchronized location");
1701
1702 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001703 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001704
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001705 const char *lparenBuf = startBuf;
1706 while (*lparenBuf != '(') lparenBuf++;
1707 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001708
1709 buf = "; objc_sync_enter(_sync_obj);\n";
1710 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1711 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1712 buf += "\n\tid sync_exit;";
1713 buf += "\n\t} _sync_exit(_sync_obj);\n";
1714
1715 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1716 // the sync expression is typically a message expression that's already
1717 // been rewritten! (which implies the SourceLocation's are invalid).
1718 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1719 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1720 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1721 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1722
1723 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1724 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1725 assert (*LBraceLocBuf == '{');
1726 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001727
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001728 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001729 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1730 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001731
1732 buf = "} catch (id e) {_rethrow = e;}\n";
1733 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001734 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001735 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001736
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001737 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001739 return 0;
1740}
1741
1742void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1743{
1744 // Perform a bottom up traversal of all children.
1745 for (Stmt::child_range CI = S->children(); CI; ++CI)
1746 if (*CI)
1747 WarnAboutReturnGotoStmts(*CI);
1748
1749 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1750 Diags.Report(Context->getFullLoc(S->getLocStart()),
1751 TryFinallyContainsReturnDiag);
1752 }
1753 return;
1754}
1755
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001756Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001757 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001758 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001759 std::string buf;
1760
1761 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001762 if (noCatch)
1763 buf = "{ id volatile _rethrow = 0;\n";
1764 else {
1765 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1766 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001767 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001768 // Get the start location and compute the semi location.
1769 SourceLocation startLoc = S->getLocStart();
1770 const char *startBuf = SM->getCharacterData(startLoc);
1771
1772 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001773 if (finalStmt)
1774 ReplaceText(startLoc, 1, buf);
1775 else
1776 // @try -> try
1777 ReplaceText(startLoc, 1, "");
1778
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001779 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1780 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001781 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001782
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001783 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001784 bool AtRemoved = false;
1785 if (catchDecl) {
1786 QualType t = catchDecl->getType();
1787 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1788 // Should be a pointer to a class.
1789 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1790 if (IDecl) {
1791 std::string Result;
1792 startBuf = SM->getCharacterData(startLoc);
1793 assert((*startBuf == '@') && "bogus @catch location");
1794 SourceLocation rParenLoc = Catch->getRParenLoc();
1795 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1796
1797 // _objc_exc_Foo *_e as argument to catch.
1798 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1799 Result += " *_"; Result += catchDecl->getNameAsString();
1800 Result += ")";
1801 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1802 // Foo *e = (Foo *)_e;
1803 Result.clear();
1804 Result = "{ ";
1805 Result += IDecl->getNameAsString();
1806 Result += " *"; Result += catchDecl->getNameAsString();
1807 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1808 Result += "_"; Result += catchDecl->getNameAsString();
1809
1810 Result += "; ";
1811 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1812 ReplaceText(lBraceLoc, 1, Result);
1813 AtRemoved = true;
1814 }
1815 }
1816 }
1817 if (!AtRemoved)
1818 // @catch -> catch
1819 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001820
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001821 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001822 if (finalStmt) {
1823 buf.clear();
1824 if (noCatch)
1825 buf = "catch (id e) {_rethrow = e;}\n";
1826 else
1827 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1828
1829 SourceLocation startFinalLoc = finalStmt->getLocStart();
1830 ReplaceText(startFinalLoc, 8, buf);
1831 Stmt *body = finalStmt->getFinallyBody();
1832 SourceLocation startFinalBodyLoc = body->getLocStart();
1833 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001834 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001835 ReplaceText(startFinalBodyLoc, 1, buf);
1836
1837 SourceLocation endFinalBodyLoc = body->getLocEnd();
1838 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001839 // Now check for any return/continue/go statements within the @try.
1840 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001841 }
1842
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001843 return 0;
1844}
1845
1846// This can't be done with ReplaceStmt(S, ThrowExpr), since
1847// the throw expression is typically a message expression that's already
1848// been rewritten! (which implies the SourceLocation's are invalid).
1849Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1850 // Get the start location and compute the semi location.
1851 SourceLocation startLoc = S->getLocStart();
1852 const char *startBuf = SM->getCharacterData(startLoc);
1853
1854 assert((*startBuf == '@') && "bogus @throw location");
1855
1856 std::string buf;
1857 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1858 if (S->getThrowExpr())
1859 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001860 else
1861 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001862
1863 // handle "@ throw" correctly.
1864 const char *wBuf = strchr(startBuf, 'w');
1865 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1866 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1867
1868 const char *semiBuf = strchr(startBuf, ';');
1869 assert((*semiBuf == ';') && "@throw: can't find ';'");
1870 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001871 if (S->getThrowExpr())
1872 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001873 return 0;
1874}
1875
1876Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1877 // Create a new string expression.
1878 QualType StrType = Context->getPointerType(Context->CharTy);
1879 std::string StrEncoding;
1880 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1881 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1882 StringLiteral::Ascii, false,
1883 StrType, SourceLocation());
1884 ReplaceStmt(Exp, Replacement);
1885
1886 // Replace this subexpr in the parent.
1887 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1888 return Replacement;
1889}
1890
1891Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1892 if (!SelGetUidFunctionDecl)
1893 SynthSelGetUidFunctionDecl();
1894 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1895 // Create a call to sel_registerName("selName").
1896 SmallVector<Expr*, 8> SelExprs;
1897 QualType argType = Context->getPointerType(Context->CharTy);
1898 SelExprs.push_back(StringLiteral::Create(*Context,
1899 Exp->getSelector().getAsString(),
1900 StringLiteral::Ascii, false,
1901 argType, SourceLocation()));
1902 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1903 &SelExprs[0], SelExprs.size());
1904 ReplaceStmt(Exp, SelExp);
1905 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1906 return SelExp;
1907}
1908
1909CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1910 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1911 SourceLocation EndLoc) {
1912 // Get the type, we will need to reference it in a couple spots.
1913 QualType msgSendType = FD->getType();
1914
1915 // Create a reference to the objc_msgSend() declaration.
1916 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001917 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001918
1919 // Now, we cast the reference to a pointer to the objc_msgSend type.
1920 QualType pToFunc = Context->getPointerType(msgSendType);
1921 ImplicitCastExpr *ICE =
1922 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1923 DRE, 0, VK_RValue);
1924
1925 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1926
1927 CallExpr *Exp =
1928 new (Context) CallExpr(*Context, ICE, args, nargs,
1929 FT->getCallResultType(*Context),
1930 VK_RValue, EndLoc);
1931 return Exp;
1932}
1933
1934static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1935 const char *&startRef, const char *&endRef) {
1936 while (startBuf < endBuf) {
1937 if (*startBuf == '<')
1938 startRef = startBuf; // mark the start.
1939 if (*startBuf == '>') {
1940 if (startRef && *startRef == '<') {
1941 endRef = startBuf; // mark the end.
1942 return true;
1943 }
1944 return false;
1945 }
1946 startBuf++;
1947 }
1948 return false;
1949}
1950
1951static void scanToNextArgument(const char *&argRef) {
1952 int angle = 0;
1953 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1954 if (*argRef == '<')
1955 angle++;
1956 else if (*argRef == '>')
1957 angle--;
1958 argRef++;
1959 }
1960 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1961}
1962
1963bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
1964 if (T->isObjCQualifiedIdType())
1965 return true;
1966 if (const PointerType *PT = T->getAs<PointerType>()) {
1967 if (PT->getPointeeType()->isObjCQualifiedIdType())
1968 return true;
1969 }
1970 if (T->isObjCObjectPointerType()) {
1971 T = T->getPointeeType();
1972 return T->isObjCQualifiedInterfaceType();
1973 }
1974 if (T->isArrayType()) {
1975 QualType ElemTy = Context->getBaseElementType(T);
1976 return needToScanForQualifiers(ElemTy);
1977 }
1978 return false;
1979}
1980
1981void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1982 QualType Type = E->getType();
1983 if (needToScanForQualifiers(Type)) {
1984 SourceLocation Loc, EndLoc;
1985
1986 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1987 Loc = ECE->getLParenLoc();
1988 EndLoc = ECE->getRParenLoc();
1989 } else {
1990 Loc = E->getLocStart();
1991 EndLoc = E->getLocEnd();
1992 }
1993 // This will defend against trying to rewrite synthesized expressions.
1994 if (Loc.isInvalid() || EndLoc.isInvalid())
1995 return;
1996
1997 const char *startBuf = SM->getCharacterData(Loc);
1998 const char *endBuf = SM->getCharacterData(EndLoc);
1999 const char *startRef = 0, *endRef = 0;
2000 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2001 // Get the locations of the startRef, endRef.
2002 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2003 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2004 // Comment out the protocol references.
2005 InsertText(LessLoc, "/*");
2006 InsertText(GreaterLoc, "*/");
2007 }
2008 }
2009}
2010
2011void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2012 SourceLocation Loc;
2013 QualType Type;
2014 const FunctionProtoType *proto = 0;
2015 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2016 Loc = VD->getLocation();
2017 Type = VD->getType();
2018 }
2019 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2020 Loc = FD->getLocation();
2021 // Check for ObjC 'id' and class types that have been adorned with protocol
2022 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2023 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2024 assert(funcType && "missing function type");
2025 proto = dyn_cast<FunctionProtoType>(funcType);
2026 if (!proto)
2027 return;
2028 Type = proto->getResultType();
2029 }
2030 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2031 Loc = FD->getLocation();
2032 Type = FD->getType();
2033 }
2034 else
2035 return;
2036
2037 if (needToScanForQualifiers(Type)) {
2038 // Since types are unique, we need to scan the buffer.
2039
2040 const char *endBuf = SM->getCharacterData(Loc);
2041 const char *startBuf = endBuf;
2042 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2043 startBuf--; // scan backward (from the decl location) for return type.
2044 const char *startRef = 0, *endRef = 0;
2045 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2046 // Get the locations of the startRef, endRef.
2047 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2048 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2049 // Comment out the protocol references.
2050 InsertText(LessLoc, "/*");
2051 InsertText(GreaterLoc, "*/");
2052 }
2053 }
2054 if (!proto)
2055 return; // most likely, was a variable
2056 // Now check arguments.
2057 const char *startBuf = SM->getCharacterData(Loc);
2058 const char *startFuncBuf = startBuf;
2059 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2060 if (needToScanForQualifiers(proto->getArgType(i))) {
2061 // Since types are unique, we need to scan the buffer.
2062
2063 const char *endBuf = startBuf;
2064 // scan forward (from the decl location) for argument types.
2065 scanToNextArgument(endBuf);
2066 const char *startRef = 0, *endRef = 0;
2067 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2068 // Get the locations of the startRef, endRef.
2069 SourceLocation LessLoc =
2070 Loc.getLocWithOffset(startRef-startFuncBuf);
2071 SourceLocation GreaterLoc =
2072 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2073 // Comment out the protocol references.
2074 InsertText(LessLoc, "/*");
2075 InsertText(GreaterLoc, "*/");
2076 }
2077 startBuf = ++endBuf;
2078 }
2079 else {
2080 // If the function name is derived from a macro expansion, then the
2081 // argument buffer will not follow the name. Need to speak with Chris.
2082 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2083 startBuf++; // scan forward (from the decl location) for argument types.
2084 startBuf++;
2085 }
2086 }
2087}
2088
2089void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2090 QualType QT = ND->getType();
2091 const Type* TypePtr = QT->getAs<Type>();
2092 if (!isa<TypeOfExprType>(TypePtr))
2093 return;
2094 while (isa<TypeOfExprType>(TypePtr)) {
2095 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2096 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2097 TypePtr = QT->getAs<Type>();
2098 }
2099 // FIXME. This will not work for multiple declarators; as in:
2100 // __typeof__(a) b,c,d;
2101 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2102 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2103 const char *startBuf = SM->getCharacterData(DeclLoc);
2104 if (ND->getInit()) {
2105 std::string Name(ND->getNameAsString());
2106 TypeAsString += " " + Name + " = ";
2107 Expr *E = ND->getInit();
2108 SourceLocation startLoc;
2109 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2110 startLoc = ECE->getLParenLoc();
2111 else
2112 startLoc = E->getLocStart();
2113 startLoc = SM->getExpansionLoc(startLoc);
2114 const char *endBuf = SM->getCharacterData(startLoc);
2115 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2116 }
2117 else {
2118 SourceLocation X = ND->getLocEnd();
2119 X = SM->getExpansionLoc(X);
2120 const char *endBuf = SM->getCharacterData(X);
2121 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2122 }
2123}
2124
2125// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2126void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2127 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2128 SmallVector<QualType, 16> ArgTys;
2129 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2130 QualType getFuncType =
2131 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2132 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2133 SourceLocation(),
2134 SourceLocation(),
2135 SelGetUidIdent, getFuncType, 0,
2136 SC_Extern,
2137 SC_None, false);
2138}
2139
2140void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2141 // declared in <objc/objc.h>
2142 if (FD->getIdentifier() &&
2143 FD->getName() == "sel_registerName") {
2144 SelGetUidFunctionDecl = FD;
2145 return;
2146 }
2147 RewriteObjCQualifiedInterfaceTypes(FD);
2148}
2149
2150void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2151 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2152 const char *argPtr = TypeString.c_str();
2153 if (!strchr(argPtr, '^')) {
2154 Str += TypeString;
2155 return;
2156 }
2157 while (*argPtr) {
2158 Str += (*argPtr == '^' ? '*' : *argPtr);
2159 argPtr++;
2160 }
2161}
2162
2163// FIXME. Consolidate this routine with RewriteBlockPointerType.
2164void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2165 ValueDecl *VD) {
2166 QualType Type = VD->getType();
2167 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2168 const char *argPtr = TypeString.c_str();
2169 int paren = 0;
2170 while (*argPtr) {
2171 switch (*argPtr) {
2172 case '(':
2173 Str += *argPtr;
2174 paren++;
2175 break;
2176 case ')':
2177 Str += *argPtr;
2178 paren--;
2179 break;
2180 case '^':
2181 Str += '*';
2182 if (paren == 1)
2183 Str += VD->getNameAsString();
2184 break;
2185 default:
2186 Str += *argPtr;
2187 break;
2188 }
2189 argPtr++;
2190 }
2191}
2192
2193
2194void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2195 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2196 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2197 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2198 if (!proto)
2199 return;
2200 QualType Type = proto->getResultType();
2201 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2202 FdStr += " ";
2203 FdStr += FD->getName();
2204 FdStr += "(";
2205 unsigned numArgs = proto->getNumArgs();
2206 for (unsigned i = 0; i < numArgs; i++) {
2207 QualType ArgType = proto->getArgType(i);
2208 RewriteBlockPointerType(FdStr, ArgType);
2209 if (i+1 < numArgs)
2210 FdStr += ", ";
2211 }
2212 FdStr += ");\n";
2213 InsertText(FunLocStart, FdStr);
2214 CurFunctionDeclToDeclareForBlock = 0;
2215}
2216
2217// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2218void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2219 if (SuperContructorFunctionDecl)
2220 return;
2221 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2222 SmallVector<QualType, 16> ArgTys;
2223 QualType argT = Context->getObjCIdType();
2224 assert(!argT.isNull() && "Can't find 'id' type");
2225 ArgTys.push_back(argT);
2226 ArgTys.push_back(argT);
2227 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2228 &ArgTys[0], ArgTys.size());
2229 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2230 SourceLocation(),
2231 SourceLocation(),
2232 msgSendIdent, msgSendType, 0,
2233 SC_Extern,
2234 SC_None, false);
2235}
2236
2237// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2238void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2239 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2240 SmallVector<QualType, 16> ArgTys;
2241 QualType argT = Context->getObjCIdType();
2242 assert(!argT.isNull() && "Can't find 'id' type");
2243 ArgTys.push_back(argT);
2244 argT = Context->getObjCSelType();
2245 assert(!argT.isNull() && "Can't find 'SEL' type");
2246 ArgTys.push_back(argT);
2247 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2248 &ArgTys[0], ArgTys.size(),
2249 true /*isVariadic*/);
2250 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2251 SourceLocation(),
2252 SourceLocation(),
2253 msgSendIdent, msgSendType, 0,
2254 SC_Extern,
2255 SC_None, false);
2256}
2257
2258// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2259void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2260 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2261 SmallVector<QualType, 16> ArgTys;
2262 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2263 SourceLocation(), SourceLocation(),
2264 &Context->Idents.get("objc_super"));
2265 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2266 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2267 ArgTys.push_back(argT);
2268 argT = Context->getObjCSelType();
2269 assert(!argT.isNull() && "Can't find 'SEL' type");
2270 ArgTys.push_back(argT);
2271 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2272 &ArgTys[0], ArgTys.size(),
2273 true /*isVariadic*/);
2274 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2275 SourceLocation(),
2276 SourceLocation(),
2277 msgSendIdent, msgSendType, 0,
2278 SC_Extern,
2279 SC_None, false);
2280}
2281
2282// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2283void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2284 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2285 SmallVector<QualType, 16> ArgTys;
2286 QualType argT = Context->getObjCIdType();
2287 assert(!argT.isNull() && "Can't find 'id' type");
2288 ArgTys.push_back(argT);
2289 argT = Context->getObjCSelType();
2290 assert(!argT.isNull() && "Can't find 'SEL' type");
2291 ArgTys.push_back(argT);
2292 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2293 &ArgTys[0], ArgTys.size(),
2294 true /*isVariadic*/);
2295 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2296 SourceLocation(),
2297 SourceLocation(),
2298 msgSendIdent, msgSendType, 0,
2299 SC_Extern,
2300 SC_None, false);
2301}
2302
2303// SynthMsgSendSuperStretFunctionDecl -
2304// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2305void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2306 IdentifierInfo *msgSendIdent =
2307 &Context->Idents.get("objc_msgSendSuper_stret");
2308 SmallVector<QualType, 16> ArgTys;
2309 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2310 SourceLocation(), SourceLocation(),
2311 &Context->Idents.get("objc_super"));
2312 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2313 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2314 ArgTys.push_back(argT);
2315 argT = Context->getObjCSelType();
2316 assert(!argT.isNull() && "Can't find 'SEL' type");
2317 ArgTys.push_back(argT);
2318 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2319 &ArgTys[0], ArgTys.size(),
2320 true /*isVariadic*/);
2321 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2322 SourceLocation(),
2323 SourceLocation(),
2324 msgSendIdent, msgSendType, 0,
2325 SC_Extern,
2326 SC_None, false);
2327}
2328
2329// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2330void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2331 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2332 SmallVector<QualType, 16> ArgTys;
2333 QualType argT = Context->getObjCIdType();
2334 assert(!argT.isNull() && "Can't find 'id' type");
2335 ArgTys.push_back(argT);
2336 argT = Context->getObjCSelType();
2337 assert(!argT.isNull() && "Can't find 'SEL' type");
2338 ArgTys.push_back(argT);
2339 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2340 &ArgTys[0], ArgTys.size(),
2341 true /*isVariadic*/);
2342 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2343 SourceLocation(),
2344 SourceLocation(),
2345 msgSendIdent, msgSendType, 0,
2346 SC_Extern,
2347 SC_None, false);
2348}
2349
2350// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2351void RewriteModernObjC::SynthGetClassFunctionDecl() {
2352 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2353 SmallVector<QualType, 16> ArgTys;
2354 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2355 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2356 &ArgTys[0], ArgTys.size());
2357 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2358 SourceLocation(),
2359 SourceLocation(),
2360 getClassIdent, getClassType, 0,
2361 SC_Extern,
2362 SC_None, false);
2363}
2364
2365// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2366void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2367 IdentifierInfo *getSuperClassIdent =
2368 &Context->Idents.get("class_getSuperclass");
2369 SmallVector<QualType, 16> ArgTys;
2370 ArgTys.push_back(Context->getObjCClassType());
2371 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2372 &ArgTys[0], ArgTys.size());
2373 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2374 SourceLocation(),
2375 SourceLocation(),
2376 getSuperClassIdent,
2377 getClassType, 0,
2378 SC_Extern,
2379 SC_None,
2380 false);
2381}
2382
2383// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2384void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2385 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2386 SmallVector<QualType, 16> ArgTys;
2387 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2388 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2389 &ArgTys[0], ArgTys.size());
2390 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2391 SourceLocation(),
2392 SourceLocation(),
2393 getClassIdent, getClassType, 0,
2394 SC_Extern,
2395 SC_None, false);
2396}
2397
2398Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2399 QualType strType = getConstantStringStructType();
2400
2401 std::string S = "__NSConstantStringImpl_";
2402
2403 std::string tmpName = InFileName;
2404 unsigned i;
2405 for (i=0; i < tmpName.length(); i++) {
2406 char c = tmpName.at(i);
2407 // replace any non alphanumeric characters with '_'.
2408 if (!isalpha(c) && (c < '0' || c > '9'))
2409 tmpName[i] = '_';
2410 }
2411 S += tmpName;
2412 S += "_";
2413 S += utostr(NumObjCStringLiterals++);
2414
2415 Preamble += "static __NSConstantStringImpl " + S;
2416 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2417 Preamble += "0x000007c8,"; // utf8_str
2418 // The pretty printer for StringLiteral handles escape characters properly.
2419 std::string prettyBufS;
2420 llvm::raw_string_ostream prettyBuf(prettyBufS);
2421 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2422 PrintingPolicy(LangOpts));
2423 Preamble += prettyBuf.str();
2424 Preamble += ",";
2425 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2426
2427 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2428 SourceLocation(), &Context->Idents.get(S),
2429 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002430 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002431 SourceLocation());
2432 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2433 Context->getPointerType(DRE->getType()),
2434 VK_RValue, OK_Ordinary,
2435 SourceLocation());
2436 // cast to NSConstantString *
2437 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2438 CK_CPointerToObjCPointerCast, Unop);
2439 ReplaceStmt(Exp, cast);
2440 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2441 return cast;
2442}
2443
2444// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2445QualType RewriteModernObjC::getSuperStructType() {
2446 if (!SuperStructDecl) {
2447 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2448 SourceLocation(), SourceLocation(),
2449 &Context->Idents.get("objc_super"));
2450 QualType FieldTypes[2];
2451
2452 // struct objc_object *receiver;
2453 FieldTypes[0] = Context->getObjCIdType();
2454 // struct objc_class *super;
2455 FieldTypes[1] = Context->getObjCClassType();
2456
2457 // Create fields
2458 for (unsigned i = 0; i < 2; ++i) {
2459 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2460 SourceLocation(),
2461 SourceLocation(), 0,
2462 FieldTypes[i], 0,
2463 /*BitWidth=*/0,
2464 /*Mutable=*/false,
2465 /*HasInit=*/false));
2466 }
2467
2468 SuperStructDecl->completeDefinition();
2469 }
2470 return Context->getTagDeclType(SuperStructDecl);
2471}
2472
2473QualType RewriteModernObjC::getConstantStringStructType() {
2474 if (!ConstantStringDecl) {
2475 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2476 SourceLocation(), SourceLocation(),
2477 &Context->Idents.get("__NSConstantStringImpl"));
2478 QualType FieldTypes[4];
2479
2480 // struct objc_object *receiver;
2481 FieldTypes[0] = Context->getObjCIdType();
2482 // int flags;
2483 FieldTypes[1] = Context->IntTy;
2484 // char *str;
2485 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2486 // long length;
2487 FieldTypes[3] = Context->LongTy;
2488
2489 // Create fields
2490 for (unsigned i = 0; i < 4; ++i) {
2491 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2492 ConstantStringDecl,
2493 SourceLocation(),
2494 SourceLocation(), 0,
2495 FieldTypes[i], 0,
2496 /*BitWidth=*/0,
2497 /*Mutable=*/true,
2498 /*HasInit=*/false));
2499 }
2500
2501 ConstantStringDecl->completeDefinition();
2502 }
2503 return Context->getTagDeclType(ConstantStringDecl);
2504}
2505
2506Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2507 SourceLocation StartLoc,
2508 SourceLocation EndLoc) {
2509 if (!SelGetUidFunctionDecl)
2510 SynthSelGetUidFunctionDecl();
2511 if (!MsgSendFunctionDecl)
2512 SynthMsgSendFunctionDecl();
2513 if (!MsgSendSuperFunctionDecl)
2514 SynthMsgSendSuperFunctionDecl();
2515 if (!MsgSendStretFunctionDecl)
2516 SynthMsgSendStretFunctionDecl();
2517 if (!MsgSendSuperStretFunctionDecl)
2518 SynthMsgSendSuperStretFunctionDecl();
2519 if (!MsgSendFpretFunctionDecl)
2520 SynthMsgSendFpretFunctionDecl();
2521 if (!GetClassFunctionDecl)
2522 SynthGetClassFunctionDecl();
2523 if (!GetSuperClassFunctionDecl)
2524 SynthGetSuperClassFunctionDecl();
2525 if (!GetMetaClassFunctionDecl)
2526 SynthGetMetaClassFunctionDecl();
2527
2528 // default to objc_msgSend().
2529 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2530 // May need to use objc_msgSend_stret() as well.
2531 FunctionDecl *MsgSendStretFlavor = 0;
2532 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2533 QualType resultType = mDecl->getResultType();
2534 if (resultType->isRecordType())
2535 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2536 else if (resultType->isRealFloatingType())
2537 MsgSendFlavor = MsgSendFpretFunctionDecl;
2538 }
2539
2540 // Synthesize a call to objc_msgSend().
2541 SmallVector<Expr*, 8> MsgExprs;
2542 switch (Exp->getReceiverKind()) {
2543 case ObjCMessageExpr::SuperClass: {
2544 MsgSendFlavor = MsgSendSuperFunctionDecl;
2545 if (MsgSendStretFlavor)
2546 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2547 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2548
2549 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2550
2551 SmallVector<Expr*, 4> InitExprs;
2552
2553 // set the receiver to self, the first argument to all methods.
2554 InitExprs.push_back(
2555 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2556 CK_BitCast,
2557 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002558 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002559 Context->getObjCIdType(),
2560 VK_RValue,
2561 SourceLocation()))
2562 ); // set the 'receiver'.
2563
2564 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2565 SmallVector<Expr*, 8> ClsExprs;
2566 QualType argType = Context->getPointerType(Context->CharTy);
2567 ClsExprs.push_back(StringLiteral::Create(*Context,
2568 ClassDecl->getIdentifier()->getName(),
2569 StringLiteral::Ascii, false,
2570 argType, SourceLocation()));
2571 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2572 &ClsExprs[0],
2573 ClsExprs.size(),
2574 StartLoc,
2575 EndLoc);
2576 // (Class)objc_getClass("CurrentClass")
2577 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2578 Context->getObjCClassType(),
2579 CK_BitCast, Cls);
2580 ClsExprs.clear();
2581 ClsExprs.push_back(ArgExpr);
2582 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2583 &ClsExprs[0], ClsExprs.size(),
2584 StartLoc, EndLoc);
2585
2586 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2587 // To turn off a warning, type-cast to 'id'
2588 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2589 NoTypeInfoCStyleCastExpr(Context,
2590 Context->getObjCIdType(),
2591 CK_BitCast, Cls));
2592 // struct objc_super
2593 QualType superType = getSuperStructType();
2594 Expr *SuperRep;
2595
2596 if (LangOpts.MicrosoftExt) {
2597 SynthSuperContructorFunctionDecl();
2598 // Simulate a contructor call...
2599 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002600 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002601 SourceLocation());
2602 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2603 InitExprs.size(),
2604 superType, VK_LValue,
2605 SourceLocation());
2606 // The code for super is a little tricky to prevent collision with
2607 // the structure definition in the header. The rewriter has it's own
2608 // internal definition (__rw_objc_super) that is uses. This is why
2609 // we need the cast below. For example:
2610 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2611 //
2612 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2613 Context->getPointerType(SuperRep->getType()),
2614 VK_RValue, OK_Ordinary,
2615 SourceLocation());
2616 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2617 Context->getPointerType(superType),
2618 CK_BitCast, SuperRep);
2619 } else {
2620 // (struct objc_super) { <exprs from above> }
2621 InitListExpr *ILE =
2622 new (Context) InitListExpr(*Context, SourceLocation(),
2623 &InitExprs[0], InitExprs.size(),
2624 SourceLocation());
2625 TypeSourceInfo *superTInfo
2626 = Context->getTrivialTypeSourceInfo(superType);
2627 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2628 superType, VK_LValue,
2629 ILE, false);
2630 // struct objc_super *
2631 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2632 Context->getPointerType(SuperRep->getType()),
2633 VK_RValue, OK_Ordinary,
2634 SourceLocation());
2635 }
2636 MsgExprs.push_back(SuperRep);
2637 break;
2638 }
2639
2640 case ObjCMessageExpr::Class: {
2641 SmallVector<Expr*, 8> ClsExprs;
2642 QualType argType = Context->getPointerType(Context->CharTy);
2643 ObjCInterfaceDecl *Class
2644 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2645 IdentifierInfo *clsName = Class->getIdentifier();
2646 ClsExprs.push_back(StringLiteral::Create(*Context,
2647 clsName->getName(),
2648 StringLiteral::Ascii, false,
2649 argType, SourceLocation()));
2650 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2651 &ClsExprs[0],
2652 ClsExprs.size(),
2653 StartLoc, EndLoc);
2654 MsgExprs.push_back(Cls);
2655 break;
2656 }
2657
2658 case ObjCMessageExpr::SuperInstance:{
2659 MsgSendFlavor = MsgSendSuperFunctionDecl;
2660 if (MsgSendStretFlavor)
2661 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2662 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2663 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2664 SmallVector<Expr*, 4> InitExprs;
2665
2666 InitExprs.push_back(
2667 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2668 CK_BitCast,
2669 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002670 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002671 Context->getObjCIdType(),
2672 VK_RValue, SourceLocation()))
2673 ); // set the 'receiver'.
2674
2675 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2676 SmallVector<Expr*, 8> ClsExprs;
2677 QualType argType = Context->getPointerType(Context->CharTy);
2678 ClsExprs.push_back(StringLiteral::Create(*Context,
2679 ClassDecl->getIdentifier()->getName(),
2680 StringLiteral::Ascii, false, argType,
2681 SourceLocation()));
2682 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2683 &ClsExprs[0],
2684 ClsExprs.size(),
2685 StartLoc, EndLoc);
2686 // (Class)objc_getClass("CurrentClass")
2687 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2688 Context->getObjCClassType(),
2689 CK_BitCast, Cls);
2690 ClsExprs.clear();
2691 ClsExprs.push_back(ArgExpr);
2692 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2693 &ClsExprs[0], ClsExprs.size(),
2694 StartLoc, EndLoc);
2695
2696 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2697 // To turn off a warning, type-cast to 'id'
2698 InitExprs.push_back(
2699 // set 'super class', using class_getSuperclass().
2700 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2701 CK_BitCast, Cls));
2702 // struct objc_super
2703 QualType superType = getSuperStructType();
2704 Expr *SuperRep;
2705
2706 if (LangOpts.MicrosoftExt) {
2707 SynthSuperContructorFunctionDecl();
2708 // Simulate a contructor call...
2709 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002710 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002711 SourceLocation());
2712 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2713 InitExprs.size(),
2714 superType, VK_LValue, SourceLocation());
2715 // The code for super is a little tricky to prevent collision with
2716 // the structure definition in the header. The rewriter has it's own
2717 // internal definition (__rw_objc_super) that is uses. This is why
2718 // we need the cast below. For example:
2719 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2720 //
2721 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2722 Context->getPointerType(SuperRep->getType()),
2723 VK_RValue, OK_Ordinary,
2724 SourceLocation());
2725 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2726 Context->getPointerType(superType),
2727 CK_BitCast, SuperRep);
2728 } else {
2729 // (struct objc_super) { <exprs from above> }
2730 InitListExpr *ILE =
2731 new (Context) InitListExpr(*Context, SourceLocation(),
2732 &InitExprs[0], InitExprs.size(),
2733 SourceLocation());
2734 TypeSourceInfo *superTInfo
2735 = Context->getTrivialTypeSourceInfo(superType);
2736 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2737 superType, VK_RValue, ILE,
2738 false);
2739 }
2740 MsgExprs.push_back(SuperRep);
2741 break;
2742 }
2743
2744 case ObjCMessageExpr::Instance: {
2745 // Remove all type-casts because it may contain objc-style types; e.g.
2746 // Foo<Proto> *.
2747 Expr *recExpr = Exp->getInstanceReceiver();
2748 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2749 recExpr = CE->getSubExpr();
2750 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2751 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2752 ? CK_BlockPointerToObjCPointerCast
2753 : CK_CPointerToObjCPointerCast;
2754
2755 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2756 CK, recExpr);
2757 MsgExprs.push_back(recExpr);
2758 break;
2759 }
2760 }
2761
2762 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2763 SmallVector<Expr*, 8> SelExprs;
2764 QualType argType = Context->getPointerType(Context->CharTy);
2765 SelExprs.push_back(StringLiteral::Create(*Context,
2766 Exp->getSelector().getAsString(),
2767 StringLiteral::Ascii, false,
2768 argType, SourceLocation()));
2769 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2770 &SelExprs[0], SelExprs.size(),
2771 StartLoc,
2772 EndLoc);
2773 MsgExprs.push_back(SelExp);
2774
2775 // Now push any user supplied arguments.
2776 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2777 Expr *userExpr = Exp->getArg(i);
2778 // Make all implicit casts explicit...ICE comes in handy:-)
2779 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2780 // Reuse the ICE type, it is exactly what the doctor ordered.
2781 QualType type = ICE->getType();
2782 if (needToScanForQualifiers(type))
2783 type = Context->getObjCIdType();
2784 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2785 (void)convertBlockPointerToFunctionPointer(type);
2786 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2787 CastKind CK;
2788 if (SubExpr->getType()->isIntegralType(*Context) &&
2789 type->isBooleanType()) {
2790 CK = CK_IntegralToBoolean;
2791 } else if (type->isObjCObjectPointerType()) {
2792 if (SubExpr->getType()->isBlockPointerType()) {
2793 CK = CK_BlockPointerToObjCPointerCast;
2794 } else if (SubExpr->getType()->isPointerType()) {
2795 CK = CK_CPointerToObjCPointerCast;
2796 } else {
2797 CK = CK_BitCast;
2798 }
2799 } else {
2800 CK = CK_BitCast;
2801 }
2802
2803 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2804 }
2805 // Make id<P...> cast into an 'id' cast.
2806 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2807 if (CE->getType()->isObjCQualifiedIdType()) {
2808 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2809 userExpr = CE->getSubExpr();
2810 CastKind CK;
2811 if (userExpr->getType()->isIntegralType(*Context)) {
2812 CK = CK_IntegralToPointer;
2813 } else if (userExpr->getType()->isBlockPointerType()) {
2814 CK = CK_BlockPointerToObjCPointerCast;
2815 } else if (userExpr->getType()->isPointerType()) {
2816 CK = CK_CPointerToObjCPointerCast;
2817 } else {
2818 CK = CK_BitCast;
2819 }
2820 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2821 CK, userExpr);
2822 }
2823 }
2824 MsgExprs.push_back(userExpr);
2825 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2826 // out the argument in the original expression (since we aren't deleting
2827 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2828 //Exp->setArg(i, 0);
2829 }
2830 // Generate the funky cast.
2831 CastExpr *cast;
2832 SmallVector<QualType, 8> ArgTypes;
2833 QualType returnType;
2834
2835 // Push 'id' and 'SEL', the 2 implicit arguments.
2836 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2837 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2838 else
2839 ArgTypes.push_back(Context->getObjCIdType());
2840 ArgTypes.push_back(Context->getObjCSelType());
2841 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2842 // Push any user argument types.
2843 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2844 E = OMD->param_end(); PI != E; ++PI) {
2845 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2846 ? Context->getObjCIdType()
2847 : (*PI)->getType();
2848 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2849 (void)convertBlockPointerToFunctionPointer(t);
2850 ArgTypes.push_back(t);
2851 }
2852 returnType = Exp->getType();
2853 convertToUnqualifiedObjCType(returnType);
2854 (void)convertBlockPointerToFunctionPointer(returnType);
2855 } else {
2856 returnType = Context->getObjCIdType();
2857 }
2858 // Get the type, we will need to reference it in a couple spots.
2859 QualType msgSendType = MsgSendFlavor->getType();
2860
2861 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002862 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002863 VK_LValue, SourceLocation());
2864
2865 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2866 // If we don't do this cast, we get the following bizarre warning/note:
2867 // xx.m:13: warning: function called through a non-compatible type
2868 // xx.m:13: note: if this code is reached, the program will abort
2869 cast = NoTypeInfoCStyleCastExpr(Context,
2870 Context->getPointerType(Context->VoidTy),
2871 CK_BitCast, DRE);
2872
2873 // Now do the "normal" pointer to function cast.
2874 QualType castType =
2875 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2876 // If we don't have a method decl, force a variadic cast.
2877 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2878 castType = Context->getPointerType(castType);
2879 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2880 cast);
2881
2882 // Don't forget the parens to enforce the proper binding.
2883 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2884
2885 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2886 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2887 MsgExprs.size(),
2888 FT->getResultType(), VK_RValue,
2889 EndLoc);
2890 Stmt *ReplacingStmt = CE;
2891 if (MsgSendStretFlavor) {
2892 // We have the method which returns a struct/union. Must also generate
2893 // call to objc_msgSend_stret and hang both varieties on a conditional
2894 // expression which dictate which one to envoke depending on size of
2895 // method's return type.
2896
2897 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002898 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2899 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002900 VK_LValue, SourceLocation());
2901 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2902 cast = NoTypeInfoCStyleCastExpr(Context,
2903 Context->getPointerType(Context->VoidTy),
2904 CK_BitCast, STDRE);
2905 // Now do the "normal" pointer to function cast.
2906 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2907 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2908 castType = Context->getPointerType(castType);
2909 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2910 cast);
2911
2912 // Don't forget the parens to enforce the proper binding.
2913 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2914
2915 FT = msgSendType->getAs<FunctionType>();
2916 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2917 MsgExprs.size(),
2918 FT->getResultType(), VK_RValue,
2919 SourceLocation());
2920
2921 // Build sizeof(returnType)
2922 UnaryExprOrTypeTraitExpr *sizeofExpr =
2923 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2924 Context->getTrivialTypeSourceInfo(returnType),
2925 Context->getSizeType(), SourceLocation(),
2926 SourceLocation());
2927 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2928 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2929 // For X86 it is more complicated and some kind of target specific routine
2930 // is needed to decide what to do.
2931 unsigned IntSize =
2932 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2933 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2934 llvm::APInt(IntSize, 8),
2935 Context->IntTy,
2936 SourceLocation());
2937 BinaryOperator *lessThanExpr =
2938 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2939 VK_RValue, OK_Ordinary, SourceLocation());
2940 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2941 ConditionalOperator *CondExpr =
2942 new (Context) ConditionalOperator(lessThanExpr,
2943 SourceLocation(), CE,
2944 SourceLocation(), STCE,
2945 returnType, VK_RValue, OK_Ordinary);
2946 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
2947 CondExpr);
2948 }
2949 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2950 return ReplacingStmt;
2951}
2952
2953Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2954 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2955 Exp->getLocEnd());
2956
2957 // Now do the actual rewrite.
2958 ReplaceStmt(Exp, ReplacingStmt);
2959
2960 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2961 return ReplacingStmt;
2962}
2963
2964// typedef struct objc_object Protocol;
2965QualType RewriteModernObjC::getProtocolType() {
2966 if (!ProtocolTypeDecl) {
2967 TypeSourceInfo *TInfo
2968 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
2969 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2970 SourceLocation(), SourceLocation(),
2971 &Context->Idents.get("Protocol"),
2972 TInfo);
2973 }
2974 return Context->getTypeDeclType(ProtocolTypeDecl);
2975}
2976
2977/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2978/// a synthesized/forward data reference (to the protocol's metadata).
2979/// The forward references (and metadata) are generated in
2980/// RewriteModernObjC::HandleTranslationUnit().
2981Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00002982 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
2983 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002984 IdentifierInfo *ID = &Context->Idents.get(Name);
2985 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2986 SourceLocation(), ID, getProtocolType(), 0,
2987 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002988 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
2989 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002990 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
2991 Context->getPointerType(DRE->getType()),
2992 VK_RValue, OK_Ordinary, SourceLocation());
2993 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2994 CK_BitCast,
2995 DerefExpr);
2996 ReplaceStmt(Exp, castExpr);
2997 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
2998 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2999 return castExpr;
3000
3001}
3002
3003bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3004 const char *endBuf) {
3005 while (startBuf < endBuf) {
3006 if (*startBuf == '#') {
3007 // Skip whitespace.
3008 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3009 ;
3010 if (!strncmp(startBuf, "if", strlen("if")) ||
3011 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3012 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3013 !strncmp(startBuf, "define", strlen("define")) ||
3014 !strncmp(startBuf, "undef", strlen("undef")) ||
3015 !strncmp(startBuf, "else", strlen("else")) ||
3016 !strncmp(startBuf, "elif", strlen("elif")) ||
3017 !strncmp(startBuf, "endif", strlen("endif")) ||
3018 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3019 !strncmp(startBuf, "include", strlen("include")) ||
3020 !strncmp(startBuf, "import", strlen("import")) ||
3021 !strncmp(startBuf, "include_next", strlen("include_next")))
3022 return true;
3023 }
3024 startBuf++;
3025 }
3026 return false;
3027}
3028
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003029/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003030/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003031bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3032 std::string &Result) {
3033 if (Type->isArrayType()) {
3034 QualType ElemTy = Context->getBaseElementType(Type);
3035 return RewriteObjCFieldDeclType(ElemTy, Result);
3036 }
3037 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003038 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3039 if (RD->isCompleteDefinition()) {
3040 if (RD->isStruct())
3041 Result += "\n\tstruct ";
3042 else if (RD->isUnion())
3043 Result += "\n\tunion ";
3044 else
3045 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003046
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003047 Result += RD->getName();
3048 if (TagsDefinedInIvarDecls.count(RD)) {
3049 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003050 Result += " ";
3051 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003052 }
3053 TagsDefinedInIvarDecls.insert(RD);
3054 Result += " {\n";
3055 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003056 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003057 FieldDecl *FD = *i;
3058 RewriteObjCFieldDecl(FD, Result);
3059 }
3060 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003061 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003062 }
3063 }
3064 else if (Type->isEnumeralType()) {
3065 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3066 if (ED->isCompleteDefinition()) {
3067 Result += "\n\tenum ";
3068 Result += ED->getName();
3069 if (TagsDefinedInIvarDecls.count(ED)) {
3070 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003071 Result += " ";
3072 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003073 }
3074 TagsDefinedInIvarDecls.insert(ED);
3075
3076 Result += " {\n";
3077 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3078 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3079 Result += "\t"; Result += EC->getName(); Result += " = ";
3080 llvm::APSInt Val = EC->getInitVal();
3081 Result += Val.toString(10);
3082 Result += ",\n";
3083 }
3084 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003085 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003086 }
3087 }
3088
3089 Result += "\t";
3090 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003091 return false;
3092}
3093
3094
3095/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3096/// It handles elaborated types, as well as enum types in the process.
3097void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3098 std::string &Result) {
3099 QualType Type = fieldDecl->getType();
3100 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003101
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003102 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3103 if (!EleboratedType)
3104 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003105 Result += Name;
3106 if (fieldDecl->isBitField()) {
3107 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3108 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003109 else if (EleboratedType && Type->isArrayType()) {
3110 CanQualType CType = Context->getCanonicalType(Type);
3111 while (isa<ArrayType>(CType)) {
3112 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3113 Result += "[";
3114 llvm::APInt Dim = CAT->getSize();
3115 Result += utostr(Dim.getZExtValue());
3116 Result += "]";
3117 }
3118 CType = CType->getAs<ArrayType>()->getElementType();
3119 }
3120 }
3121
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003122 Result += ";\n";
3123}
3124
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003125/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3126/// an objective-c class with ivars.
3127void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3128 std::string &Result) {
3129 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3130 assert(CDecl->getName() != "" &&
3131 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003132 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003133 SmallVector<ObjCIvarDecl *, 8> IVars;
3134 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003135 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003136 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003137
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003138 SourceLocation LocStart = CDecl->getLocStart();
3139 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003140
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003141 const char *startBuf = SM->getCharacterData(LocStart);
3142 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003143
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003144 // If no ivars and no root or if its root, directly or indirectly,
3145 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003146 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003147 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3148 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3149 ReplaceText(LocStart, endBuf-startBuf, Result);
3150 return;
3151 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003152
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003153 Result += "\nstruct ";
3154 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003155 Result += "_IMPL {\n";
3156
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003157 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003158 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3159 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3160 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003161 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003162 TagsDefinedInIvarDecls.clear();
3163 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3164 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003165
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003166 Result += "};\n";
3167 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3168 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003169 // Mark this struct as having been generated.
3170 if (!ObjCSynthesizedStructs.insert(CDecl))
3171 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003172}
3173
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003174static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3175 ObjCIvarDecl *IvarDecl, std::string &Result) {
3176 Result += "OBJC_IVAR_$_";
3177 Result += IDecl->getName();
3178 Result += "$";
3179 Result += IvarDecl->getName();
3180}
3181
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003182/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3183/// have been referenced in an ivar access expression.
3184void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3185 std::string &Result) {
3186 // write out ivar offset symbols which have been referenced in an ivar
3187 // access expression.
3188 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3189 if (Ivars.empty())
3190 return;
3191 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3192 e = Ivars.end(); i != e; i++) {
3193 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003194 Result += "\n";
3195 if (LangOpts.MicrosoftExt)
3196 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3197 if (LangOpts.MicrosoftExt &&
3198 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3199 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3200 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3201 if (CDecl->getImplementation())
3202 Result += "__declspec(dllexport) ";
3203 }
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003204 Result += "extern unsigned long ";
3205 WriteInternalIvarName(CDecl, IvarDecl, Result);
3206 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003207 }
3208}
3209
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003210//===----------------------------------------------------------------------===//
3211// Meta Data Emission
3212//===----------------------------------------------------------------------===//
3213
3214
3215/// RewriteImplementations - This routine rewrites all method implementations
3216/// and emits meta-data.
3217
3218void RewriteModernObjC::RewriteImplementations() {
3219 int ClsDefCount = ClassImplementation.size();
3220 int CatDefCount = CategoryImplementation.size();
3221
3222 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003223 for (int i = 0; i < ClsDefCount; i++) {
3224 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3225 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3226 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003227 assert(false &&
3228 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003229 RewriteImplementationDecl(OIMP);
3230 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003231
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003232 for (int i = 0; i < CatDefCount; i++) {
3233 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3234 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3235 if (CDecl->isImplicitInterfaceDecl())
3236 assert(false &&
3237 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003238 RewriteImplementationDecl(CIMP);
3239 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003240}
3241
3242void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3243 const std::string &Name,
3244 ValueDecl *VD, bool def) {
3245 assert(BlockByRefDeclNo.count(VD) &&
3246 "RewriteByRefString: ByRef decl missing");
3247 if (def)
3248 ResultStr += "struct ";
3249 ResultStr += "__Block_byref_" + Name +
3250 "_" + utostr(BlockByRefDeclNo[VD]) ;
3251}
3252
3253static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3254 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3255 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3256 return false;
3257}
3258
3259std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3260 StringRef funcName,
3261 std::string Tag) {
3262 const FunctionType *AFT = CE->getFunctionType();
3263 QualType RT = AFT->getResultType();
3264 std::string StructRef = "struct " + Tag;
3265 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3266 funcName.str() + "_" + "block_func_" + utostr(i);
3267
3268 BlockDecl *BD = CE->getBlockDecl();
3269
3270 if (isa<FunctionNoProtoType>(AFT)) {
3271 // No user-supplied arguments. Still need to pass in a pointer to the
3272 // block (to reference imported block decl refs).
3273 S += "(" + StructRef + " *__cself)";
3274 } else if (BD->param_empty()) {
3275 S += "(" + StructRef + " *__cself)";
3276 } else {
3277 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3278 assert(FT && "SynthesizeBlockFunc: No function proto");
3279 S += '(';
3280 // first add the implicit argument.
3281 S += StructRef + " *__cself, ";
3282 std::string ParamStr;
3283 for (BlockDecl::param_iterator AI = BD->param_begin(),
3284 E = BD->param_end(); AI != E; ++AI) {
3285 if (AI != BD->param_begin()) S += ", ";
3286 ParamStr = (*AI)->getNameAsString();
3287 QualType QT = (*AI)->getType();
3288 if (convertBlockPointerToFunctionPointer(QT))
3289 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3290 else
3291 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3292 S += ParamStr;
3293 }
3294 if (FT->isVariadic()) {
3295 if (!BD->param_empty()) S += ", ";
3296 S += "...";
3297 }
3298 S += ')';
3299 }
3300 S += " {\n";
3301
3302 // Create local declarations to avoid rewriting all closure decl ref exprs.
3303 // First, emit a declaration for all "by ref" decls.
3304 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3305 E = BlockByRefDecls.end(); I != E; ++I) {
3306 S += " ";
3307 std::string Name = (*I)->getNameAsString();
3308 std::string TypeString;
3309 RewriteByRefString(TypeString, Name, (*I));
3310 TypeString += " *";
3311 Name = TypeString + Name;
3312 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3313 }
3314 // Next, emit a declaration for all "by copy" declarations.
3315 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3316 E = BlockByCopyDecls.end(); I != E; ++I) {
3317 S += " ";
3318 // Handle nested closure invocation. For example:
3319 //
3320 // void (^myImportedClosure)(void);
3321 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3322 //
3323 // void (^anotherClosure)(void);
3324 // anotherClosure = ^(void) {
3325 // myImportedClosure(); // import and invoke the closure
3326 // };
3327 //
3328 if (isTopLevelBlockPointerType((*I)->getType())) {
3329 RewriteBlockPointerTypeVariable(S, (*I));
3330 S += " = (";
3331 RewriteBlockPointerType(S, (*I)->getType());
3332 S += ")";
3333 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3334 }
3335 else {
3336 std::string Name = (*I)->getNameAsString();
3337 QualType QT = (*I)->getType();
3338 if (HasLocalVariableExternalStorage(*I))
3339 QT = Context->getPointerType(QT);
3340 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3341 S += Name + " = __cself->" +
3342 (*I)->getNameAsString() + "; // bound by copy\n";
3343 }
3344 }
3345 std::string RewrittenStr = RewrittenBlockExprs[CE];
3346 const char *cstr = RewrittenStr.c_str();
3347 while (*cstr++ != '{') ;
3348 S += cstr;
3349 S += "\n";
3350 return S;
3351}
3352
3353std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3354 StringRef funcName,
3355 std::string Tag) {
3356 std::string StructRef = "struct " + Tag;
3357 std::string S = "static void __";
3358
3359 S += funcName;
3360 S += "_block_copy_" + utostr(i);
3361 S += "(" + StructRef;
3362 S += "*dst, " + StructRef;
3363 S += "*src) {";
3364 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3365 E = ImportedBlockDecls.end(); I != E; ++I) {
3366 ValueDecl *VD = (*I);
3367 S += "_Block_object_assign((void*)&dst->";
3368 S += (*I)->getNameAsString();
3369 S += ", (void*)src->";
3370 S += (*I)->getNameAsString();
3371 if (BlockByRefDeclsPtrSet.count((*I)))
3372 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3373 else if (VD->getType()->isBlockPointerType())
3374 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3375 else
3376 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3377 }
3378 S += "}\n";
3379
3380 S += "\nstatic void __";
3381 S += funcName;
3382 S += "_block_dispose_" + utostr(i);
3383 S += "(" + StructRef;
3384 S += "*src) {";
3385 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3386 E = ImportedBlockDecls.end(); I != E; ++I) {
3387 ValueDecl *VD = (*I);
3388 S += "_Block_object_dispose((void*)src->";
3389 S += (*I)->getNameAsString();
3390 if (BlockByRefDeclsPtrSet.count((*I)))
3391 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3392 else if (VD->getType()->isBlockPointerType())
3393 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3394 else
3395 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3396 }
3397 S += "}\n";
3398 return S;
3399}
3400
3401std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3402 std::string Desc) {
3403 std::string S = "\nstruct " + Tag;
3404 std::string Constructor = " " + Tag;
3405
3406 S += " {\n struct __block_impl impl;\n";
3407 S += " struct " + Desc;
3408 S += "* Desc;\n";
3409
3410 Constructor += "(void *fp, "; // Invoke function pointer.
3411 Constructor += "struct " + Desc; // Descriptor pointer.
3412 Constructor += " *desc";
3413
3414 if (BlockDeclRefs.size()) {
3415 // Output all "by copy" declarations.
3416 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3417 E = BlockByCopyDecls.end(); I != E; ++I) {
3418 S += " ";
3419 std::string FieldName = (*I)->getNameAsString();
3420 std::string ArgName = "_" + FieldName;
3421 // Handle nested closure invocation. For example:
3422 //
3423 // void (^myImportedBlock)(void);
3424 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3425 //
3426 // void (^anotherBlock)(void);
3427 // anotherBlock = ^(void) {
3428 // myImportedBlock(); // import and invoke the closure
3429 // };
3430 //
3431 if (isTopLevelBlockPointerType((*I)->getType())) {
3432 S += "struct __block_impl *";
3433 Constructor += ", void *" + ArgName;
3434 } else {
3435 QualType QT = (*I)->getType();
3436 if (HasLocalVariableExternalStorage(*I))
3437 QT = Context->getPointerType(QT);
3438 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3439 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3440 Constructor += ", " + ArgName;
3441 }
3442 S += FieldName + ";\n";
3443 }
3444 // Output all "by ref" declarations.
3445 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3446 E = BlockByRefDecls.end(); I != E; ++I) {
3447 S += " ";
3448 std::string FieldName = (*I)->getNameAsString();
3449 std::string ArgName = "_" + FieldName;
3450 {
3451 std::string TypeString;
3452 RewriteByRefString(TypeString, FieldName, (*I));
3453 TypeString += " *";
3454 FieldName = TypeString + FieldName;
3455 ArgName = TypeString + ArgName;
3456 Constructor += ", " + ArgName;
3457 }
3458 S += FieldName + "; // by ref\n";
3459 }
3460 // Finish writing the constructor.
3461 Constructor += ", int flags=0)";
3462 // Initialize all "by copy" arguments.
3463 bool firsTime = true;
3464 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3465 E = BlockByCopyDecls.end(); I != E; ++I) {
3466 std::string Name = (*I)->getNameAsString();
3467 if (firsTime) {
3468 Constructor += " : ";
3469 firsTime = false;
3470 }
3471 else
3472 Constructor += ", ";
3473 if (isTopLevelBlockPointerType((*I)->getType()))
3474 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3475 else
3476 Constructor += Name + "(_" + Name + ")";
3477 }
3478 // Initialize all "by ref" arguments.
3479 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3480 E = BlockByRefDecls.end(); I != E; ++I) {
3481 std::string Name = (*I)->getNameAsString();
3482 if (firsTime) {
3483 Constructor += " : ";
3484 firsTime = false;
3485 }
3486 else
3487 Constructor += ", ";
3488 Constructor += Name + "(_" + Name + "->__forwarding)";
3489 }
3490
3491 Constructor += " {\n";
3492 if (GlobalVarDecl)
3493 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3494 else
3495 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3496 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3497
3498 Constructor += " Desc = desc;\n";
3499 } else {
3500 // Finish writing the constructor.
3501 Constructor += ", int flags=0) {\n";
3502 if (GlobalVarDecl)
3503 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3504 else
3505 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3506 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3507 Constructor += " Desc = desc;\n";
3508 }
3509 Constructor += " ";
3510 Constructor += "}\n";
3511 S += Constructor;
3512 S += "};\n";
3513 return S;
3514}
3515
3516std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3517 std::string ImplTag, int i,
3518 StringRef FunName,
3519 unsigned hasCopy) {
3520 std::string S = "\nstatic struct " + DescTag;
3521
3522 S += " {\n unsigned long reserved;\n";
3523 S += " unsigned long Block_size;\n";
3524 if (hasCopy) {
3525 S += " void (*copy)(struct ";
3526 S += ImplTag; S += "*, struct ";
3527 S += ImplTag; S += "*);\n";
3528
3529 S += " void (*dispose)(struct ";
3530 S += ImplTag; S += "*);\n";
3531 }
3532 S += "} ";
3533
3534 S += DescTag + "_DATA = { 0, sizeof(struct ";
3535 S += ImplTag + ")";
3536 if (hasCopy) {
3537 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3538 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3539 }
3540 S += "};\n";
3541 return S;
3542}
3543
3544void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3545 StringRef FunName) {
3546 // Insert declaration for the function in which block literal is used.
3547 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3548 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3549 bool RewriteSC = (GlobalVarDecl &&
3550 !Blocks.empty() &&
3551 GlobalVarDecl->getStorageClass() == SC_Static &&
3552 GlobalVarDecl->getType().getCVRQualifiers());
3553 if (RewriteSC) {
3554 std::string SC(" void __");
3555 SC += GlobalVarDecl->getNameAsString();
3556 SC += "() {}";
3557 InsertText(FunLocStart, SC);
3558 }
3559
3560 // Insert closures that were part of the function.
3561 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3562 CollectBlockDeclRefInfo(Blocks[i]);
3563 // Need to copy-in the inner copied-in variables not actually used in this
3564 // block.
3565 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003566 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003567 ValueDecl *VD = Exp->getDecl();
3568 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003569 if (!VD->hasAttr<BlocksAttr>()) {
3570 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3571 BlockByCopyDeclsPtrSet.insert(VD);
3572 BlockByCopyDecls.push_back(VD);
3573 }
3574 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003575 }
John McCallf4b88a42012-03-10 09:33:50 +00003576
3577 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003578 BlockByRefDeclsPtrSet.insert(VD);
3579 BlockByRefDecls.push_back(VD);
3580 }
John McCallf4b88a42012-03-10 09:33:50 +00003581
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003582 // imported objects in the inner blocks not used in the outer
3583 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003584 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003585 VD->getType()->isBlockPointerType())
3586 ImportedBlockDecls.insert(VD);
3587 }
3588
3589 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3590 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3591
3592 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3593
3594 InsertText(FunLocStart, CI);
3595
3596 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3597
3598 InsertText(FunLocStart, CF);
3599
3600 if (ImportedBlockDecls.size()) {
3601 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3602 InsertText(FunLocStart, HF);
3603 }
3604 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3605 ImportedBlockDecls.size() > 0);
3606 InsertText(FunLocStart, BD);
3607
3608 BlockDeclRefs.clear();
3609 BlockByRefDecls.clear();
3610 BlockByRefDeclsPtrSet.clear();
3611 BlockByCopyDecls.clear();
3612 BlockByCopyDeclsPtrSet.clear();
3613 ImportedBlockDecls.clear();
3614 }
3615 if (RewriteSC) {
3616 // Must insert any 'const/volatile/static here. Since it has been
3617 // removed as result of rewriting of block literals.
3618 std::string SC;
3619 if (GlobalVarDecl->getStorageClass() == SC_Static)
3620 SC = "static ";
3621 if (GlobalVarDecl->getType().isConstQualified())
3622 SC += "const ";
3623 if (GlobalVarDecl->getType().isVolatileQualified())
3624 SC += "volatile ";
3625 if (GlobalVarDecl->getType().isRestrictQualified())
3626 SC += "restrict ";
3627 InsertText(FunLocStart, SC);
3628 }
3629
3630 Blocks.clear();
3631 InnerDeclRefsCount.clear();
3632 InnerDeclRefs.clear();
3633 RewrittenBlockExprs.clear();
3634}
3635
3636void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3637 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3638 StringRef FuncName = FD->getName();
3639
3640 SynthesizeBlockLiterals(FunLocStart, FuncName);
3641}
3642
3643static void BuildUniqueMethodName(std::string &Name,
3644 ObjCMethodDecl *MD) {
3645 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3646 Name = IFace->getName();
3647 Name += "__" + MD->getSelector().getAsString();
3648 // Convert colons to underscores.
3649 std::string::size_type loc = 0;
3650 while ((loc = Name.find(":", loc)) != std::string::npos)
3651 Name.replace(loc, 1, "_");
3652}
3653
3654void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3655 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3656 //SourceLocation FunLocStart = MD->getLocStart();
3657 SourceLocation FunLocStart = MD->getLocStart();
3658 std::string FuncName;
3659 BuildUniqueMethodName(FuncName, MD);
3660 SynthesizeBlockLiterals(FunLocStart, FuncName);
3661}
3662
3663void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3664 for (Stmt::child_range CI = S->children(); CI; ++CI)
3665 if (*CI) {
3666 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3667 GetBlockDeclRefExprs(CBE->getBody());
3668 else
3669 GetBlockDeclRefExprs(*CI);
3670 }
3671 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003672 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3673 if (DRE->refersToEnclosingLocal() &&
3674 HasLocalVariableExternalStorage(DRE->getDecl())) {
3675 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003676 }
3677
3678 return;
3679}
3680
3681void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003682 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003683 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3684 for (Stmt::child_range CI = S->children(); CI; ++CI)
3685 if (*CI) {
3686 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3687 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3688 GetInnerBlockDeclRefExprs(CBE->getBody(),
3689 InnerBlockDeclRefs,
3690 InnerContexts);
3691 }
3692 else
3693 GetInnerBlockDeclRefExprs(*CI,
3694 InnerBlockDeclRefs,
3695 InnerContexts);
3696
3697 }
3698 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003699 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3700 if (DRE->refersToEnclosingLocal()) {
3701 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3702 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3703 InnerBlockDeclRefs.push_back(DRE);
3704 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3705 if (Var->isFunctionOrMethodVarDecl())
3706 ImportedLocalExternalDecls.insert(Var);
3707 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003708 }
3709
3710 return;
3711}
3712
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003713/// convertObjCTypeToCStyleType - This routine converts such objc types
3714/// as qualified objects, and blocks to their closest c/c++ types that
3715/// it can. It returns true if input type was modified.
3716bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3717 QualType oldT = T;
3718 convertBlockPointerToFunctionPointer(T);
3719 if (T->isFunctionPointerType()) {
3720 QualType PointeeTy;
3721 if (const PointerType* PT = T->getAs<PointerType>()) {
3722 PointeeTy = PT->getPointeeType();
3723 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3724 T = convertFunctionTypeOfBlocks(FT);
3725 T = Context->getPointerType(T);
3726 }
3727 }
3728 }
3729
3730 convertToUnqualifiedObjCType(T);
3731 return T != oldT;
3732}
3733
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003734/// convertFunctionTypeOfBlocks - This routine converts a function type
3735/// whose result type may be a block pointer or whose argument type(s)
3736/// might be block pointers to an equivalent function type replacing
3737/// all block pointers to function pointers.
3738QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3739 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3740 // FTP will be null for closures that don't take arguments.
3741 // Generate a funky cast.
3742 SmallVector<QualType, 8> ArgTypes;
3743 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003744 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003745
3746 if (FTP) {
3747 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3748 E = FTP->arg_type_end(); I && (I != E); ++I) {
3749 QualType t = *I;
3750 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003751 if (convertObjCTypeToCStyleType(t))
3752 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003753 ArgTypes.push_back(t);
3754 }
3755 }
3756 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003757 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003758 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3759 else FuncType = QualType(FT, 0);
3760 return FuncType;
3761}
3762
3763Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3764 // Navigate to relevant type information.
3765 const BlockPointerType *CPT = 0;
3766
3767 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3768 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003769 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3770 CPT = MExpr->getType()->getAs<BlockPointerType>();
3771 }
3772 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3773 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3774 }
3775 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3776 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3777 else if (const ConditionalOperator *CEXPR =
3778 dyn_cast<ConditionalOperator>(BlockExp)) {
3779 Expr *LHSExp = CEXPR->getLHS();
3780 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3781 Expr *RHSExp = CEXPR->getRHS();
3782 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3783 Expr *CONDExp = CEXPR->getCond();
3784 ConditionalOperator *CondExpr =
3785 new (Context) ConditionalOperator(CONDExp,
3786 SourceLocation(), cast<Expr>(LHSStmt),
3787 SourceLocation(), cast<Expr>(RHSStmt),
3788 Exp->getType(), VK_RValue, OK_Ordinary);
3789 return CondExpr;
3790 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3791 CPT = IRE->getType()->getAs<BlockPointerType>();
3792 } else if (const PseudoObjectExpr *POE
3793 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3794 CPT = POE->getType()->castAs<BlockPointerType>();
3795 } else {
3796 assert(1 && "RewriteBlockClass: Bad type");
3797 }
3798 assert(CPT && "RewriteBlockClass: Bad type");
3799 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3800 assert(FT && "RewriteBlockClass: Bad type");
3801 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3802 // FTP will be null for closures that don't take arguments.
3803
3804 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3805 SourceLocation(), SourceLocation(),
3806 &Context->Idents.get("__block_impl"));
3807 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3808
3809 // Generate a funky cast.
3810 SmallVector<QualType, 8> ArgTypes;
3811
3812 // Push the block argument type.
3813 ArgTypes.push_back(PtrBlock);
3814 if (FTP) {
3815 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3816 E = FTP->arg_type_end(); I && (I != E); ++I) {
3817 QualType t = *I;
3818 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3819 if (!convertBlockPointerToFunctionPointer(t))
3820 convertToUnqualifiedObjCType(t);
3821 ArgTypes.push_back(t);
3822 }
3823 }
3824 // Now do the pointer to function cast.
3825 QualType PtrToFuncCastType
3826 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3827
3828 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3829
3830 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3831 CK_BitCast,
3832 const_cast<Expr*>(BlockExp));
3833 // Don't forget the parens to enforce the proper binding.
3834 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3835 BlkCast);
3836 //PE->dump();
3837
3838 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3839 SourceLocation(),
3840 &Context->Idents.get("FuncPtr"),
3841 Context->VoidPtrTy, 0,
3842 /*BitWidth=*/0, /*Mutable=*/true,
3843 /*HasInit=*/false);
3844 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3845 FD->getType(), VK_LValue,
3846 OK_Ordinary);
3847
3848
3849 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3850 CK_BitCast, ME);
3851 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3852
3853 SmallVector<Expr*, 8> BlkExprs;
3854 // Add the implicit argument.
3855 BlkExprs.push_back(BlkCast);
3856 // Add the user arguments.
3857 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3858 E = Exp->arg_end(); I != E; ++I) {
3859 BlkExprs.push_back(*I);
3860 }
3861 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3862 BlkExprs.size(),
3863 Exp->getType(), VK_RValue,
3864 SourceLocation());
3865 return CE;
3866}
3867
3868// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003869// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003870// For example:
3871//
3872// int main() {
3873// __block Foo *f;
3874// __block int i;
3875//
3876// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003877// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003878// i = 77;
3879// };
3880//}
John McCallf4b88a42012-03-10 09:33:50 +00003881Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003882 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3883 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003884 ValueDecl *VD = DeclRefExp->getDecl();
3885 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003886
3887 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3888 SourceLocation(),
3889 &Context->Idents.get("__forwarding"),
3890 Context->VoidPtrTy, 0,
3891 /*BitWidth=*/0, /*Mutable=*/true,
3892 /*HasInit=*/false);
3893 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3894 FD, SourceLocation(),
3895 FD->getType(), VK_LValue,
3896 OK_Ordinary);
3897
3898 StringRef Name = VD->getName();
3899 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3900 &Context->Idents.get(Name),
3901 Context->VoidPtrTy, 0,
3902 /*BitWidth=*/0, /*Mutable=*/true,
3903 /*HasInit=*/false);
3904 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3905 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3906
3907
3908
3909 // Need parens to enforce precedence.
3910 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3911 DeclRefExp->getExprLoc(),
3912 ME);
3913 ReplaceStmt(DeclRefExp, PE);
3914 return PE;
3915}
3916
3917// Rewrites the imported local variable V with external storage
3918// (static, extern, etc.) as *V
3919//
3920Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3921 ValueDecl *VD = DRE->getDecl();
3922 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3923 if (!ImportedLocalExternalDecls.count(Var))
3924 return DRE;
3925 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3926 VK_LValue, OK_Ordinary,
3927 DRE->getLocation());
3928 // Need parens to enforce precedence.
3929 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3930 Exp);
3931 ReplaceStmt(DRE, PE);
3932 return PE;
3933}
3934
3935void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3936 SourceLocation LocStart = CE->getLParenLoc();
3937 SourceLocation LocEnd = CE->getRParenLoc();
3938
3939 // Need to avoid trying to rewrite synthesized casts.
3940 if (LocStart.isInvalid())
3941 return;
3942 // Need to avoid trying to rewrite casts contained in macros.
3943 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3944 return;
3945
3946 const char *startBuf = SM->getCharacterData(LocStart);
3947 const char *endBuf = SM->getCharacterData(LocEnd);
3948 QualType QT = CE->getType();
3949 const Type* TypePtr = QT->getAs<Type>();
3950 if (isa<TypeOfExprType>(TypePtr)) {
3951 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3952 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3953 std::string TypeAsString = "(";
3954 RewriteBlockPointerType(TypeAsString, QT);
3955 TypeAsString += ")";
3956 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3957 return;
3958 }
3959 // advance the location to startArgList.
3960 const char *argPtr = startBuf;
3961
3962 while (*argPtr++ && (argPtr < endBuf)) {
3963 switch (*argPtr) {
3964 case '^':
3965 // Replace the '^' with '*'.
3966 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3967 ReplaceText(LocStart, 1, "*");
3968 break;
3969 }
3970 }
3971 return;
3972}
3973
3974void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3975 SourceLocation DeclLoc = FD->getLocation();
3976 unsigned parenCount = 0;
3977
3978 // We have 1 or more arguments that have closure pointers.
3979 const char *startBuf = SM->getCharacterData(DeclLoc);
3980 const char *startArgList = strchr(startBuf, '(');
3981
3982 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3983
3984 parenCount++;
3985 // advance the location to startArgList.
3986 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3987 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3988
3989 const char *argPtr = startArgList;
3990
3991 while (*argPtr++ && parenCount) {
3992 switch (*argPtr) {
3993 case '^':
3994 // Replace the '^' with '*'.
3995 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3996 ReplaceText(DeclLoc, 1, "*");
3997 break;
3998 case '(':
3999 parenCount++;
4000 break;
4001 case ')':
4002 parenCount--;
4003 break;
4004 }
4005 }
4006 return;
4007}
4008
4009bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4010 const FunctionProtoType *FTP;
4011 const PointerType *PT = QT->getAs<PointerType>();
4012 if (PT) {
4013 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4014 } else {
4015 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4016 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4017 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4018 }
4019 if (FTP) {
4020 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4021 E = FTP->arg_type_end(); I != E; ++I)
4022 if (isTopLevelBlockPointerType(*I))
4023 return true;
4024 }
4025 return false;
4026}
4027
4028bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4029 const FunctionProtoType *FTP;
4030 const PointerType *PT = QT->getAs<PointerType>();
4031 if (PT) {
4032 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4033 } else {
4034 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4035 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4036 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4037 }
4038 if (FTP) {
4039 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4040 E = FTP->arg_type_end(); I != E; ++I) {
4041 if ((*I)->isObjCQualifiedIdType())
4042 return true;
4043 if ((*I)->isObjCObjectPointerType() &&
4044 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4045 return true;
4046 }
4047
4048 }
4049 return false;
4050}
4051
4052void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4053 const char *&RParen) {
4054 const char *argPtr = strchr(Name, '(');
4055 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4056
4057 LParen = argPtr; // output the start.
4058 argPtr++; // skip past the left paren.
4059 unsigned parenCount = 1;
4060
4061 while (*argPtr && parenCount) {
4062 switch (*argPtr) {
4063 case '(': parenCount++; break;
4064 case ')': parenCount--; break;
4065 default: break;
4066 }
4067 if (parenCount) argPtr++;
4068 }
4069 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4070 RParen = argPtr; // output the end
4071}
4072
4073void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4075 RewriteBlockPointerFunctionArgs(FD);
4076 return;
4077 }
4078 // Handle Variables and Typedefs.
4079 SourceLocation DeclLoc = ND->getLocation();
4080 QualType DeclT;
4081 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4082 DeclT = VD->getType();
4083 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4084 DeclT = TDD->getUnderlyingType();
4085 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4086 DeclT = FD->getType();
4087 else
4088 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4089
4090 const char *startBuf = SM->getCharacterData(DeclLoc);
4091 const char *endBuf = startBuf;
4092 // scan backward (from the decl location) for the end of the previous decl.
4093 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4094 startBuf--;
4095 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4096 std::string buf;
4097 unsigned OrigLength=0;
4098 // *startBuf != '^' if we are dealing with a pointer to function that
4099 // may take block argument types (which will be handled below).
4100 if (*startBuf == '^') {
4101 // Replace the '^' with '*', computing a negative offset.
4102 buf = '*';
4103 startBuf++;
4104 OrigLength++;
4105 }
4106 while (*startBuf != ')') {
4107 buf += *startBuf;
4108 startBuf++;
4109 OrigLength++;
4110 }
4111 buf += ')';
4112 OrigLength++;
4113
4114 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4115 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4116 // Replace the '^' with '*' for arguments.
4117 // Replace id<P> with id/*<>*/
4118 DeclLoc = ND->getLocation();
4119 startBuf = SM->getCharacterData(DeclLoc);
4120 const char *argListBegin, *argListEnd;
4121 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4122 while (argListBegin < argListEnd) {
4123 if (*argListBegin == '^')
4124 buf += '*';
4125 else if (*argListBegin == '<') {
4126 buf += "/*";
4127 buf += *argListBegin++;
4128 OrigLength++;;
4129 while (*argListBegin != '>') {
4130 buf += *argListBegin++;
4131 OrigLength++;
4132 }
4133 buf += *argListBegin;
4134 buf += "*/";
4135 }
4136 else
4137 buf += *argListBegin;
4138 argListBegin++;
4139 OrigLength++;
4140 }
4141 buf += ')';
4142 OrigLength++;
4143 }
4144 ReplaceText(Start, OrigLength, buf);
4145
4146 return;
4147}
4148
4149
4150/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4151/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4152/// struct Block_byref_id_object *src) {
4153/// _Block_object_assign (&_dest->object, _src->object,
4154/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4155/// [|BLOCK_FIELD_IS_WEAK]) // object
4156/// _Block_object_assign(&_dest->object, _src->object,
4157/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4158/// [|BLOCK_FIELD_IS_WEAK]) // block
4159/// }
4160/// And:
4161/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4162/// _Block_object_dispose(_src->object,
4163/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4164/// [|BLOCK_FIELD_IS_WEAK]) // object
4165/// _Block_object_dispose(_src->object,
4166/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4167/// [|BLOCK_FIELD_IS_WEAK]) // block
4168/// }
4169
4170std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4171 int flag) {
4172 std::string S;
4173 if (CopyDestroyCache.count(flag))
4174 return S;
4175 CopyDestroyCache.insert(flag);
4176 S = "static void __Block_byref_id_object_copy_";
4177 S += utostr(flag);
4178 S += "(void *dst, void *src) {\n";
4179
4180 // offset into the object pointer is computed as:
4181 // void * + void* + int + int + void* + void *
4182 unsigned IntSize =
4183 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4184 unsigned VoidPtrSize =
4185 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4186
4187 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4188 S += " _Block_object_assign((char*)dst + ";
4189 S += utostr(offset);
4190 S += ", *(void * *) ((char*)src + ";
4191 S += utostr(offset);
4192 S += "), ";
4193 S += utostr(flag);
4194 S += ");\n}\n";
4195
4196 S += "static void __Block_byref_id_object_dispose_";
4197 S += utostr(flag);
4198 S += "(void *src) {\n";
4199 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4200 S += utostr(offset);
4201 S += "), ";
4202 S += utostr(flag);
4203 S += ");\n}\n";
4204 return S;
4205}
4206
4207/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4208/// the declaration into:
4209/// struct __Block_byref_ND {
4210/// void *__isa; // NULL for everything except __weak pointers
4211/// struct __Block_byref_ND *__forwarding;
4212/// int32_t __flags;
4213/// int32_t __size;
4214/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4215/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4216/// typex ND;
4217/// };
4218///
4219/// It then replaces declaration of ND variable with:
4220/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4221/// __size=sizeof(struct __Block_byref_ND),
4222/// ND=initializer-if-any};
4223///
4224///
4225void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4226 // Insert declaration for the function in which block literal is
4227 // used.
4228 if (CurFunctionDeclToDeclareForBlock)
4229 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4230 int flag = 0;
4231 int isa = 0;
4232 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4233 if (DeclLoc.isInvalid())
4234 // If type location is missing, it is because of missing type (a warning).
4235 // Use variable's location which is good for this case.
4236 DeclLoc = ND->getLocation();
4237 const char *startBuf = SM->getCharacterData(DeclLoc);
4238 SourceLocation X = ND->getLocEnd();
4239 X = SM->getExpansionLoc(X);
4240 const char *endBuf = SM->getCharacterData(X);
4241 std::string Name(ND->getNameAsString());
4242 std::string ByrefType;
4243 RewriteByRefString(ByrefType, Name, ND, true);
4244 ByrefType += " {\n";
4245 ByrefType += " void *__isa;\n";
4246 RewriteByRefString(ByrefType, Name, ND);
4247 ByrefType += " *__forwarding;\n";
4248 ByrefType += " int __flags;\n";
4249 ByrefType += " int __size;\n";
4250 // Add void *__Block_byref_id_object_copy;
4251 // void *__Block_byref_id_object_dispose; if needed.
4252 QualType Ty = ND->getType();
4253 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4254 if (HasCopyAndDispose) {
4255 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4256 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4257 }
4258
4259 QualType T = Ty;
4260 (void)convertBlockPointerToFunctionPointer(T);
4261 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4262
4263 ByrefType += " " + Name + ";\n";
4264 ByrefType += "};\n";
4265 // Insert this type in global scope. It is needed by helper function.
4266 SourceLocation FunLocStart;
4267 if (CurFunctionDef)
4268 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4269 else {
4270 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4271 FunLocStart = CurMethodDef->getLocStart();
4272 }
4273 InsertText(FunLocStart, ByrefType);
4274 if (Ty.isObjCGCWeak()) {
4275 flag |= BLOCK_FIELD_IS_WEAK;
4276 isa = 1;
4277 }
4278
4279 if (HasCopyAndDispose) {
4280 flag = BLOCK_BYREF_CALLER;
4281 QualType Ty = ND->getType();
4282 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4283 if (Ty->isBlockPointerType())
4284 flag |= BLOCK_FIELD_IS_BLOCK;
4285 else
4286 flag |= BLOCK_FIELD_IS_OBJECT;
4287 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4288 if (!HF.empty())
4289 InsertText(FunLocStart, HF);
4290 }
4291
4292 // struct __Block_byref_ND ND =
4293 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4294 // initializer-if-any};
4295 bool hasInit = (ND->getInit() != 0);
4296 unsigned flags = 0;
4297 if (HasCopyAndDispose)
4298 flags |= BLOCK_HAS_COPY_DISPOSE;
4299 Name = ND->getNameAsString();
4300 ByrefType.clear();
4301 RewriteByRefString(ByrefType, Name, ND);
4302 std::string ForwardingCastType("(");
4303 ForwardingCastType += ByrefType + " *)";
4304 if (!hasInit) {
4305 ByrefType += " " + Name + " = {(void*)";
4306 ByrefType += utostr(isa);
4307 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4308 ByrefType += utostr(flags);
4309 ByrefType += ", ";
4310 ByrefType += "sizeof(";
4311 RewriteByRefString(ByrefType, Name, ND);
4312 ByrefType += ")";
4313 if (HasCopyAndDispose) {
4314 ByrefType += ", __Block_byref_id_object_copy_";
4315 ByrefType += utostr(flag);
4316 ByrefType += ", __Block_byref_id_object_dispose_";
4317 ByrefType += utostr(flag);
4318 }
4319 ByrefType += "};\n";
4320 unsigned nameSize = Name.size();
4321 // for block or function pointer declaration. Name is aleady
4322 // part of the declaration.
4323 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4324 nameSize = 1;
4325 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4326 }
4327 else {
4328 SourceLocation startLoc;
4329 Expr *E = ND->getInit();
4330 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4331 startLoc = ECE->getLParenLoc();
4332 else
4333 startLoc = E->getLocStart();
4334 startLoc = SM->getExpansionLoc(startLoc);
4335 endBuf = SM->getCharacterData(startLoc);
4336 ByrefType += " " + Name;
4337 ByrefType += " = {(void*)";
4338 ByrefType += utostr(isa);
4339 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4340 ByrefType += utostr(flags);
4341 ByrefType += ", ";
4342 ByrefType += "sizeof(";
4343 RewriteByRefString(ByrefType, Name, ND);
4344 ByrefType += "), ";
4345 if (HasCopyAndDispose) {
4346 ByrefType += "__Block_byref_id_object_copy_";
4347 ByrefType += utostr(flag);
4348 ByrefType += ", __Block_byref_id_object_dispose_";
4349 ByrefType += utostr(flag);
4350 ByrefType += ", ";
4351 }
4352 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4353
4354 // Complete the newly synthesized compound expression by inserting a right
4355 // curly brace before the end of the declaration.
4356 // FIXME: This approach avoids rewriting the initializer expression. It
4357 // also assumes there is only one declarator. For example, the following
4358 // isn't currently supported by this routine (in general):
4359 //
4360 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4361 //
4362 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4363 const char *semiBuf = strchr(startInitializerBuf, ';');
4364 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4365 SourceLocation semiLoc =
4366 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4367
4368 InsertText(semiLoc, "}");
4369 }
4370 return;
4371}
4372
4373void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4374 // Add initializers for any closure decl refs.
4375 GetBlockDeclRefExprs(Exp->getBody());
4376 if (BlockDeclRefs.size()) {
4377 // Unique all "by copy" declarations.
4378 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004379 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004380 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4381 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4382 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4383 }
4384 }
4385 // Unique all "by ref" declarations.
4386 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004387 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004388 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4389 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4390 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4391 }
4392 }
4393 // Find any imported blocks...they will need special attention.
4394 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004395 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004396 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4397 BlockDeclRefs[i]->getType()->isBlockPointerType())
4398 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4399 }
4400}
4401
4402FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4403 IdentifierInfo *ID = &Context->Idents.get(name);
4404 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4405 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4406 SourceLocation(), ID, FType, 0, SC_Extern,
4407 SC_None, false, false);
4408}
4409
4410Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004411 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004412 const BlockDecl *block = Exp->getBlockDecl();
4413 Blocks.push_back(Exp);
4414
4415 CollectBlockDeclRefInfo(Exp);
4416
4417 // Add inner imported variables now used in current block.
4418 int countOfInnerDecls = 0;
4419 if (!InnerBlockDeclRefs.empty()) {
4420 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004421 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004422 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004423 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004424 // We need to save the copied-in variables in nested
4425 // blocks because it is needed at the end for some of the API generations.
4426 // See SynthesizeBlockLiterals routine.
4427 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4428 BlockDeclRefs.push_back(Exp);
4429 BlockByCopyDeclsPtrSet.insert(VD);
4430 BlockByCopyDecls.push_back(VD);
4431 }
John McCallf4b88a42012-03-10 09:33:50 +00004432 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004433 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4434 BlockDeclRefs.push_back(Exp);
4435 BlockByRefDeclsPtrSet.insert(VD);
4436 BlockByRefDecls.push_back(VD);
4437 }
4438 }
4439 // Find any imported blocks...they will need special attention.
4440 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004441 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004442 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4443 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4444 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4445 }
4446 InnerDeclRefsCount.push_back(countOfInnerDecls);
4447
4448 std::string FuncName;
4449
4450 if (CurFunctionDef)
4451 FuncName = CurFunctionDef->getNameAsString();
4452 else if (CurMethodDef)
4453 BuildUniqueMethodName(FuncName, CurMethodDef);
4454 else if (GlobalVarDecl)
4455 FuncName = std::string(GlobalVarDecl->getNameAsString());
4456
4457 std::string BlockNumber = utostr(Blocks.size()-1);
4458
4459 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4460 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4461
4462 // Get a pointer to the function type so we can cast appropriately.
4463 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4464 QualType FType = Context->getPointerType(BFT);
4465
4466 FunctionDecl *FD;
4467 Expr *NewRep;
4468
4469 // Simulate a contructor call...
4470 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004471 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004472 SourceLocation());
4473
4474 SmallVector<Expr*, 4> InitExprs;
4475
4476 // Initialize the block function.
4477 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004478 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4479 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004480 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4481 CK_BitCast, Arg);
4482 InitExprs.push_back(castExpr);
4483
4484 // Initialize the block descriptor.
4485 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4486
4487 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4488 SourceLocation(), SourceLocation(),
4489 &Context->Idents.get(DescData.c_str()),
4490 Context->VoidPtrTy, 0,
4491 SC_Static, SC_None);
4492 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004493 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004494 Context->VoidPtrTy,
4495 VK_LValue,
4496 SourceLocation()),
4497 UO_AddrOf,
4498 Context->getPointerType(Context->VoidPtrTy),
4499 VK_RValue, OK_Ordinary,
4500 SourceLocation());
4501 InitExprs.push_back(DescRefExpr);
4502
4503 // Add initializers for any closure decl refs.
4504 if (BlockDeclRefs.size()) {
4505 Expr *Exp;
4506 // Output all "by copy" declarations.
4507 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4508 E = BlockByCopyDecls.end(); I != E; ++I) {
4509 if (isObjCType((*I)->getType())) {
4510 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4511 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004512 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4513 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004514 if (HasLocalVariableExternalStorage(*I)) {
4515 QualType QT = (*I)->getType();
4516 QT = Context->getPointerType(QT);
4517 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4518 OK_Ordinary, SourceLocation());
4519 }
4520 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4521 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004522 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4523 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004524 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4525 CK_BitCast, Arg);
4526 } else {
4527 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004528 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4529 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004530 if (HasLocalVariableExternalStorage(*I)) {
4531 QualType QT = (*I)->getType();
4532 QT = Context->getPointerType(QT);
4533 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4534 OK_Ordinary, SourceLocation());
4535 }
4536
4537 }
4538 InitExprs.push_back(Exp);
4539 }
4540 // Output all "by ref" declarations.
4541 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4542 E = BlockByRefDecls.end(); I != E; ++I) {
4543 ValueDecl *ND = (*I);
4544 std::string Name(ND->getNameAsString());
4545 std::string RecName;
4546 RewriteByRefString(RecName, Name, ND, true);
4547 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4548 + sizeof("struct"));
4549 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4550 SourceLocation(), SourceLocation(),
4551 II);
4552 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4553 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4554
4555 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004556 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004557 SourceLocation());
4558 bool isNestedCapturedVar = false;
4559 if (block)
4560 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4561 ce = block->capture_end(); ci != ce; ++ci) {
4562 const VarDecl *variable = ci->getVariable();
4563 if (variable == ND && ci->isNested()) {
4564 assert (ci->isByRef() &&
4565 "SynthBlockInitExpr - captured block variable is not byref");
4566 isNestedCapturedVar = true;
4567 break;
4568 }
4569 }
4570 // captured nested byref variable has its address passed. Do not take
4571 // its address again.
4572 if (!isNestedCapturedVar)
4573 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4574 Context->getPointerType(Exp->getType()),
4575 VK_RValue, OK_Ordinary, SourceLocation());
4576 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4577 InitExprs.push_back(Exp);
4578 }
4579 }
4580 if (ImportedBlockDecls.size()) {
4581 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4582 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4583 unsigned IntSize =
4584 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4585 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4586 Context->IntTy, SourceLocation());
4587 InitExprs.push_back(FlagExp);
4588 }
4589 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4590 FType, VK_LValue, SourceLocation());
4591 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4592 Context->getPointerType(NewRep->getType()),
4593 VK_RValue, OK_Ordinary, SourceLocation());
4594 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4595 NewRep);
4596 BlockDeclRefs.clear();
4597 BlockByRefDecls.clear();
4598 BlockByRefDeclsPtrSet.clear();
4599 BlockByCopyDecls.clear();
4600 BlockByCopyDeclsPtrSet.clear();
4601 ImportedBlockDecls.clear();
4602 return NewRep;
4603}
4604
4605bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4606 if (const ObjCForCollectionStmt * CS =
4607 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4608 return CS->getElement() == DS;
4609 return false;
4610}
4611
4612//===----------------------------------------------------------------------===//
4613// Function Body / Expression rewriting
4614//===----------------------------------------------------------------------===//
4615
4616Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4617 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4618 isa<DoStmt>(S) || isa<ForStmt>(S))
4619 Stmts.push_back(S);
4620 else if (isa<ObjCForCollectionStmt>(S)) {
4621 Stmts.push_back(S);
4622 ObjCBcLabelNo.push_back(++BcLabelCount);
4623 }
4624
4625 // Pseudo-object operations and ivar references need special
4626 // treatment because we're going to recursively rewrite them.
4627 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4628 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4629 return RewritePropertyOrImplicitSetter(PseudoOp);
4630 } else {
4631 return RewritePropertyOrImplicitGetter(PseudoOp);
4632 }
4633 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4634 return RewriteObjCIvarRefExpr(IvarRefExpr);
4635 }
4636
4637 SourceRange OrigStmtRange = S->getSourceRange();
4638
4639 // Perform a bottom up rewrite of all children.
4640 for (Stmt::child_range CI = S->children(); CI; ++CI)
4641 if (*CI) {
4642 Stmt *childStmt = (*CI);
4643 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4644 if (newStmt) {
4645 *CI = newStmt;
4646 }
4647 }
4648
4649 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004650 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004651 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4652 InnerContexts.insert(BE->getBlockDecl());
4653 ImportedLocalExternalDecls.clear();
4654 GetInnerBlockDeclRefExprs(BE->getBody(),
4655 InnerBlockDeclRefs, InnerContexts);
4656 // Rewrite the block body in place.
4657 Stmt *SaveCurrentBody = CurrentBody;
4658 CurrentBody = BE->getBody();
4659 PropParentMap = 0;
4660 // block literal on rhs of a property-dot-sytax assignment
4661 // must be replaced by its synthesize ast so getRewrittenText
4662 // works as expected. In this case, what actually ends up on RHS
4663 // is the blockTranscribed which is the helper function for the
4664 // block literal; as in: self.c = ^() {[ace ARR];};
4665 bool saveDisableReplaceStmt = DisableReplaceStmt;
4666 DisableReplaceStmt = false;
4667 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4668 DisableReplaceStmt = saveDisableReplaceStmt;
4669 CurrentBody = SaveCurrentBody;
4670 PropParentMap = 0;
4671 ImportedLocalExternalDecls.clear();
4672 // Now we snarf the rewritten text and stash it away for later use.
4673 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4674 RewrittenBlockExprs[BE] = Str;
4675
4676 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4677
4678 //blockTranscribed->dump();
4679 ReplaceStmt(S, blockTranscribed);
4680 return blockTranscribed;
4681 }
4682 // Handle specific things.
4683 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4684 return RewriteAtEncode(AtEncode);
4685
4686 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4687 return RewriteAtSelector(AtSelector);
4688
4689 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4690 return RewriteObjCStringLiteral(AtString);
4691
4692 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4693#if 0
4694 // Before we rewrite it, put the original message expression in a comment.
4695 SourceLocation startLoc = MessExpr->getLocStart();
4696 SourceLocation endLoc = MessExpr->getLocEnd();
4697
4698 const char *startBuf = SM->getCharacterData(startLoc);
4699 const char *endBuf = SM->getCharacterData(endLoc);
4700
4701 std::string messString;
4702 messString += "// ";
4703 messString.append(startBuf, endBuf-startBuf+1);
4704 messString += "\n";
4705
4706 // FIXME: Missing definition of
4707 // InsertText(clang::SourceLocation, char const*, unsigned int).
4708 // InsertText(startLoc, messString.c_str(), messString.size());
4709 // Tried this, but it didn't work either...
4710 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4711#endif
4712 return RewriteMessageExpr(MessExpr);
4713 }
4714
4715 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4716 return RewriteObjCTryStmt(StmtTry);
4717
4718 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4719 return RewriteObjCSynchronizedStmt(StmtTry);
4720
4721 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4722 return RewriteObjCThrowStmt(StmtThrow);
4723
4724 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4725 return RewriteObjCProtocolExpr(ProtocolExp);
4726
4727 if (ObjCForCollectionStmt *StmtForCollection =
4728 dyn_cast<ObjCForCollectionStmt>(S))
4729 return RewriteObjCForCollectionStmt(StmtForCollection,
4730 OrigStmtRange.getEnd());
4731 if (BreakStmt *StmtBreakStmt =
4732 dyn_cast<BreakStmt>(S))
4733 return RewriteBreakStmt(StmtBreakStmt);
4734 if (ContinueStmt *StmtContinueStmt =
4735 dyn_cast<ContinueStmt>(S))
4736 return RewriteContinueStmt(StmtContinueStmt);
4737
4738 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4739 // and cast exprs.
4740 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4741 // FIXME: What we're doing here is modifying the type-specifier that
4742 // precedes the first Decl. In the future the DeclGroup should have
4743 // a separate type-specifier that we can rewrite.
4744 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4745 // the context of an ObjCForCollectionStmt. For example:
4746 // NSArray *someArray;
4747 // for (id <FooProtocol> index in someArray) ;
4748 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4749 // and it depends on the original text locations/positions.
4750 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4751 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4752
4753 // Blocks rewrite rules.
4754 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4755 DI != DE; ++DI) {
4756 Decl *SD = *DI;
4757 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4758 if (isTopLevelBlockPointerType(ND->getType()))
4759 RewriteBlockPointerDecl(ND);
4760 else if (ND->getType()->isFunctionPointerType())
4761 CheckFunctionPointerDecl(ND->getType(), ND);
4762 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4763 if (VD->hasAttr<BlocksAttr>()) {
4764 static unsigned uniqueByrefDeclCount = 0;
4765 assert(!BlockByRefDeclNo.count(ND) &&
4766 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4767 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4768 RewriteByRefVar(VD);
4769 }
4770 else
4771 RewriteTypeOfDecl(VD);
4772 }
4773 }
4774 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4775 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4776 RewriteBlockPointerDecl(TD);
4777 else if (TD->getUnderlyingType()->isFunctionPointerType())
4778 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4779 }
4780 }
4781 }
4782
4783 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4784 RewriteObjCQualifiedInterfaceTypes(CE);
4785
4786 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4787 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4788 assert(!Stmts.empty() && "Statement stack is empty");
4789 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4790 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4791 && "Statement stack mismatch");
4792 Stmts.pop_back();
4793 }
4794 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004795 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4796 ValueDecl *VD = DRE->getDecl();
4797 if (VD->hasAttr<BlocksAttr>())
4798 return RewriteBlockDeclRefExpr(DRE);
4799 if (HasLocalVariableExternalStorage(VD))
4800 return RewriteLocalVariableExternalStorage(DRE);
4801 }
4802
4803 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4804 if (CE->getCallee()->getType()->isBlockPointerType()) {
4805 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4806 ReplaceStmt(S, BlockCall);
4807 return BlockCall;
4808 }
4809 }
4810 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4811 RewriteCastExpr(CE);
4812 }
4813#if 0
4814 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4815 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4816 ICE->getSubExpr(),
4817 SourceLocation());
4818 // Get the new text.
4819 std::string SStr;
4820 llvm::raw_string_ostream Buf(SStr);
4821 Replacement->printPretty(Buf, *Context);
4822 const std::string &Str = Buf.str();
4823
4824 printf("CAST = %s\n", &Str[0]);
4825 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4826 delete S;
4827 return Replacement;
4828 }
4829#endif
4830 // Return this stmt unmodified.
4831 return S;
4832}
4833
4834void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4835 for (RecordDecl::field_iterator i = RD->field_begin(),
4836 e = RD->field_end(); i != e; ++i) {
4837 FieldDecl *FD = *i;
4838 if (isTopLevelBlockPointerType(FD->getType()))
4839 RewriteBlockPointerDecl(FD);
4840 if (FD->getType()->isObjCQualifiedIdType() ||
4841 FD->getType()->isObjCQualifiedInterfaceType())
4842 RewriteObjCQualifiedInterfaceTypes(FD);
4843 }
4844}
4845
4846/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4847/// main file of the input.
4848void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4849 switch (D->getKind()) {
4850 case Decl::Function: {
4851 FunctionDecl *FD = cast<FunctionDecl>(D);
4852 if (FD->isOverloadedOperator())
4853 return;
4854
4855 // Since function prototypes don't have ParmDecl's, we check the function
4856 // prototype. This enables us to rewrite function declarations and
4857 // definitions using the same code.
4858 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4859
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004860 if (!FD->isThisDeclarationADefinition())
4861 break;
4862
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004863 // FIXME: If this should support Obj-C++, support CXXTryStmt
4864 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4865 CurFunctionDef = FD;
4866 CurFunctionDeclToDeclareForBlock = FD;
4867 CurrentBody = Body;
4868 Body =
4869 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4870 FD->setBody(Body);
4871 CurrentBody = 0;
4872 if (PropParentMap) {
4873 delete PropParentMap;
4874 PropParentMap = 0;
4875 }
4876 // This synthesizes and inserts the block "impl" struct, invoke function,
4877 // and any copy/dispose helper functions.
4878 InsertBlockLiteralsWithinFunction(FD);
4879 CurFunctionDef = 0;
4880 CurFunctionDeclToDeclareForBlock = 0;
4881 }
4882 break;
4883 }
4884 case Decl::ObjCMethod: {
4885 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4886 if (CompoundStmt *Body = MD->getCompoundBody()) {
4887 CurMethodDef = MD;
4888 CurrentBody = Body;
4889 Body =
4890 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4891 MD->setBody(Body);
4892 CurrentBody = 0;
4893 if (PropParentMap) {
4894 delete PropParentMap;
4895 PropParentMap = 0;
4896 }
4897 InsertBlockLiteralsWithinMethod(MD);
4898 CurMethodDef = 0;
4899 }
4900 break;
4901 }
4902 case Decl::ObjCImplementation: {
4903 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4904 ClassImplementation.push_back(CI);
4905 break;
4906 }
4907 case Decl::ObjCCategoryImpl: {
4908 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4909 CategoryImplementation.push_back(CI);
4910 break;
4911 }
4912 case Decl::Var: {
4913 VarDecl *VD = cast<VarDecl>(D);
4914 RewriteObjCQualifiedInterfaceTypes(VD);
4915 if (isTopLevelBlockPointerType(VD->getType()))
4916 RewriteBlockPointerDecl(VD);
4917 else if (VD->getType()->isFunctionPointerType()) {
4918 CheckFunctionPointerDecl(VD->getType(), VD);
4919 if (VD->getInit()) {
4920 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4921 RewriteCastExpr(CE);
4922 }
4923 }
4924 } else if (VD->getType()->isRecordType()) {
4925 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4926 if (RD->isCompleteDefinition())
4927 RewriteRecordBody(RD);
4928 }
4929 if (VD->getInit()) {
4930 GlobalVarDecl = VD;
4931 CurrentBody = VD->getInit();
4932 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4933 CurrentBody = 0;
4934 if (PropParentMap) {
4935 delete PropParentMap;
4936 PropParentMap = 0;
4937 }
4938 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4939 GlobalVarDecl = 0;
4940
4941 // This is needed for blocks.
4942 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4943 RewriteCastExpr(CE);
4944 }
4945 }
4946 break;
4947 }
4948 case Decl::TypeAlias:
4949 case Decl::Typedef: {
4950 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4951 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4952 RewriteBlockPointerDecl(TD);
4953 else if (TD->getUnderlyingType()->isFunctionPointerType())
4954 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4955 }
4956 break;
4957 }
4958 case Decl::CXXRecord:
4959 case Decl::Record: {
4960 RecordDecl *RD = cast<RecordDecl>(D);
4961 if (RD->isCompleteDefinition())
4962 RewriteRecordBody(RD);
4963 break;
4964 }
4965 default:
4966 break;
4967 }
4968 // Nothing yet.
4969}
4970
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00004971/// Write_ProtocolExprReferencedMetadata - This routine writer out the
4972/// protocol reference symbols in the for of:
4973/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
4974static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
4975 ObjCProtocolDecl *PDecl,
4976 std::string &Result) {
4977 // Also output .objc_protorefs$B section and its meta-data.
4978 if (Context->getLangOpts().MicrosoftExt)
4979 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
4980 Result += "struct _protocol_t *";
4981 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
4982 Result += PDecl->getNameAsString();
4983 Result += " = &";
4984 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
4985 Result += ";\n";
4986}
4987
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004988void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
4989 if (Diags.hasErrorOccurred())
4990 return;
4991
4992 RewriteInclude();
4993
4994 // Here's a great place to add any extra declarations that may be needed.
4995 // Write out meta data for each @protocol(<expr>).
4996 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00004997 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00004998 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00004999 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5000 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005001
5002 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005003 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5004 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5005 // Write struct declaration for the class matching its ivar declarations.
5006 // Note that for modern abi, this is postponed until the end of TU
5007 // because class extensions and the implementation might declare their own
5008 // private ivars.
5009 RewriteInterfaceDecl(CDecl);
5010 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005011
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005012 if (ClassImplementation.size() || CategoryImplementation.size())
5013 RewriteImplementations();
5014
5015 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5016 // we are done.
5017 if (const RewriteBuffer *RewriteBuf =
5018 Rewrite.getRewriteBufferFor(MainFileID)) {
5019 //printf("Changed:\n");
5020 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5021 } else {
5022 llvm::errs() << "No changes\n";
5023 }
5024
5025 if (ClassImplementation.size() || CategoryImplementation.size() ||
5026 ProtocolExprDecls.size()) {
5027 // Rewrite Objective-c meta data*
5028 std::string ResultStr;
5029 RewriteMetaDataIntoBuffer(ResultStr);
5030 // Emit metadata.
5031 *OutFile << ResultStr;
5032 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005033 // Emit ImageInfo;
5034 {
5035 std::string ResultStr;
5036 WriteImageInfo(ResultStr);
5037 *OutFile << ResultStr;
5038 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005039 OutFile->flush();
5040}
5041
5042void RewriteModernObjC::Initialize(ASTContext &context) {
5043 InitializeCommon(context);
5044
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005045 Preamble += "#ifndef __OBJC2__\n";
5046 Preamble += "#define __OBJC2__\n";
5047 Preamble += "#endif\n";
5048
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005049 // declaring objc_selector outside the parameter list removes a silly
5050 // scope related warning...
5051 if (IsHeader)
5052 Preamble = "#pragma once\n";
5053 Preamble += "struct objc_selector; struct objc_class;\n";
5054 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5055 Preamble += "struct objc_object *superClass; ";
5056 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005057 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005058 // These are currently generated.
5059 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005060 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005061 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5062 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005063 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5064 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005065 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005066 // These are generated but not necessary for functionality.
5067 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5068 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005069 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5070 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005071 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005072
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005073 // These need be generated for performance. Currently they are not,
5074 // using API calls instead.
5075 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5076 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5077 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5078
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005079 // Add a constructor for creating temporary objects.
5080 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5081 ": ";
5082 Preamble += "object(o), superClass(s) {} ";
5083 }
5084 Preamble += "};\n";
5085 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5086 Preamble += "typedef struct objc_object Protocol;\n";
5087 Preamble += "#define _REWRITER_typedef_Protocol\n";
5088 Preamble += "#endif\n";
5089 if (LangOpts.MicrosoftExt) {
5090 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5091 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5092 } else
5093 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5094 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5095 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5096 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5097 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5098 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5099 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5101 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5102 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5103 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5105 Preamble += "(const char *);\n";
5106 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5107 Preamble += "(struct objc_class *);\n";
5108 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5109 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005110 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005111 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005112 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5113 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005114 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5115 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5116 Preamble += "struct __objcFastEnumerationState {\n\t";
5117 Preamble += "unsigned long state;\n\t";
5118 Preamble += "void **itemsPtr;\n\t";
5119 Preamble += "unsigned long *mutationsPtr;\n\t";
5120 Preamble += "unsigned long extra[5];\n};\n";
5121 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5122 Preamble += "#define __FASTENUMERATIONSTATE\n";
5123 Preamble += "#endif\n";
5124 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5125 Preamble += "struct __NSConstantStringImpl {\n";
5126 Preamble += " int *isa;\n";
5127 Preamble += " int flags;\n";
5128 Preamble += " char *str;\n";
5129 Preamble += " long length;\n";
5130 Preamble += "};\n";
5131 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5132 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5133 Preamble += "#else\n";
5134 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5135 Preamble += "#endif\n";
5136 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5137 Preamble += "#endif\n";
5138 // Blocks preamble.
5139 Preamble += "#ifndef BLOCK_IMPL\n";
5140 Preamble += "#define BLOCK_IMPL\n";
5141 Preamble += "struct __block_impl {\n";
5142 Preamble += " void *isa;\n";
5143 Preamble += " int Flags;\n";
5144 Preamble += " int Reserved;\n";
5145 Preamble += " void *FuncPtr;\n";
5146 Preamble += "};\n";
5147 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5148 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5149 Preamble += "extern \"C\" __declspec(dllexport) "
5150 "void _Block_object_assign(void *, const void *, const int);\n";
5151 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5152 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5153 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5154 Preamble += "#else\n";
5155 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5156 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5157 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5158 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5159 Preamble += "#endif\n";
5160 Preamble += "#endif\n";
5161 if (LangOpts.MicrosoftExt) {
5162 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5163 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5164 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5165 Preamble += "#define __attribute__(X)\n";
5166 Preamble += "#endif\n";
5167 Preamble += "#define __weak\n";
5168 }
5169 else {
5170 Preamble += "#define __block\n";
5171 Preamble += "#define __weak\n";
5172 }
5173 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5174 // as this avoids warning in any 64bit/32bit compilation model.
5175 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5176}
5177
5178/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5179/// ivar offset.
5180void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5181 std::string &Result) {
5182 if (ivar->isBitField()) {
5183 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5184 // place all bitfields at offset 0.
5185 Result += "0";
5186 } else {
5187 Result += "__OFFSETOFIVAR__(struct ";
5188 Result += ivar->getContainingInterface()->getNameAsString();
5189 if (LangOpts.MicrosoftExt)
5190 Result += "_IMPL";
5191 Result += ", ";
5192 Result += ivar->getNameAsString();
5193 Result += ")";
5194 }
5195}
5196
5197/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5198/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005199/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005200/// char *attributes;
5201/// }
5202
5203/// struct _prop_list_t {
5204/// uint32_t entsize; // sizeof(struct _prop_t)
5205/// uint32_t count_of_properties;
5206/// struct _prop_t prop_list[count_of_properties];
5207/// }
5208
5209/// struct _protocol_t;
5210
5211/// struct _protocol_list_t {
5212/// long protocol_count; // Note, this is 32/64 bit
5213/// struct _protocol_t * protocol_list[protocol_count];
5214/// }
5215
5216/// struct _objc_method {
5217/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005218/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005219/// char *_imp;
5220/// }
5221
5222/// struct _method_list_t {
5223/// uint32_t entsize; // sizeof(struct _objc_method)
5224/// uint32_t method_count;
5225/// struct _objc_method method_list[method_count];
5226/// }
5227
5228/// struct _protocol_t {
5229/// id isa; // NULL
5230/// const char * const protocol_name;
5231/// const struct _protocol_list_t * protocol_list; // super protocols
5232/// const struct method_list_t * const instance_methods;
5233/// const struct method_list_t * const class_methods;
5234/// const struct method_list_t *optionalInstanceMethods;
5235/// const struct method_list_t *optionalClassMethods;
5236/// const struct _prop_list_t * properties;
5237/// const uint32_t size; // sizeof(struct _protocol_t)
5238/// const uint32_t flags; // = 0
5239/// const char ** extendedMethodTypes;
5240/// }
5241
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005242/// struct _ivar_t {
5243/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005244/// const char *name;
5245/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005246/// uint32_t alignment;
5247/// uint32_t size;
5248/// }
5249
5250/// struct _ivar_list_t {
5251/// uint32 entsize; // sizeof(struct _ivar_t)
5252/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005253/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005254/// }
5255
5256/// struct _class_ro_t {
5257/// uint32_t const flags;
5258/// uint32_t const instanceStart;
5259/// uint32_t const instanceSize;
5260/// uint32_t const reserved; // only when building for 64bit targets
5261/// const uint8_t * const ivarLayout;
5262/// const char *const name;
5263/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005264/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005265/// const struct _ivar_list_t *const ivars;
5266/// const uint8_t * const weakIvarLayout;
5267/// const struct _prop_list_t * const properties;
5268/// }
5269
5270/// struct _class_t {
5271/// struct _class_t *isa;
5272/// struct _class_t * const superclass;
5273/// void *cache;
5274/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005275/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005276/// }
5277
5278/// struct _category_t {
5279/// const char * const name;
5280/// struct _class_t *const cls;
5281/// const struct _method_list_t * const instance_methods;
5282/// const struct _method_list_t * const class_methods;
5283/// const struct _protocol_list_t * const protocols;
5284/// const struct _prop_list_t * const properties;
5285/// }
5286
5287/// MessageRefTy - LLVM for:
5288/// struct _message_ref_t {
5289/// IMP messenger;
5290/// SEL name;
5291/// };
5292
5293/// SuperMessageRefTy - LLVM for:
5294/// struct _super_message_ref_t {
5295/// SUPER_IMP messenger;
5296/// SEL name;
5297/// };
5298
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005299static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005300 static bool meta_data_declared = false;
5301 if (meta_data_declared)
5302 return;
5303
5304 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005305 Result += "\tconst char *name;\n";
5306 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005307 Result += "};\n";
5308
5309 Result += "\nstruct _protocol_t;\n";
5310
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005311 Result += "\nstruct _objc_method {\n";
5312 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005313 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005314 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005315 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005316
5317 Result += "\nstruct _protocol_t {\n";
5318 Result += "\tvoid * isa; // NULL\n";
5319 Result += "\tconst char * const protocol_name;\n";
5320 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5321 Result += "\tconst struct method_list_t * const instance_methods;\n";
5322 Result += "\tconst struct method_list_t * const class_methods;\n";
5323 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5324 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5325 Result += "\tconst struct _prop_list_t * properties;\n";
5326 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5327 Result += "\tconst unsigned int flags; // = 0\n";
5328 Result += "\tconst char ** extendedMethodTypes;\n";
5329 Result += "};\n";
5330
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005331 Result += "\nstruct _ivar_t {\n";
5332 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005333 Result += "\tconst char *name;\n";
5334 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005335 Result += "\tunsigned int alignment;\n";
5336 Result += "\tunsigned int size;\n";
5337 Result += "};\n";
5338
5339 Result += "\nstruct _class_ro_t {\n";
5340 Result += "\tunsigned int const flags;\n";
5341 Result += "\tunsigned int instanceStart;\n";
5342 Result += "\tunsigned int const instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005343 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5344 if (Triple.getArch() == llvm::Triple::x86_64)
5345 Result += "\tunsigned int const reserved;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005346 Result += "\tconst unsigned char * const ivarLayout;\n";
5347 Result += "\tconst char *const name;\n";
5348 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5349 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5350 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5351 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5352 Result += "\tconst struct _prop_list_t *const properties;\n";
5353 Result += "};\n";
5354
5355 Result += "\nstruct _class_t {\n";
5356 Result += "\tstruct _class_t *isa;\n";
5357 Result += "\tstruct _class_t *const superclass;\n";
5358 Result += "\tvoid *cache;\n";
5359 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005360 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005361 Result += "};\n";
5362
5363 Result += "\nstruct _category_t {\n";
5364 Result += "\tconst char * const name;\n";
5365 Result += "\tstruct _class_t *const cls;\n";
5366 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5367 Result += "\tconst struct _method_list_t *const class_methods;\n";
5368 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5369 Result += "\tconst struct _prop_list_t *const properties;\n";
5370 Result += "};\n";
5371
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005372 Result += "extern void *_objc_empty_cache;\n";
5373 Result += "extern void *_objc_empty_vtable;\n";
5374
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005375 meta_data_declared = true;
5376}
5377
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005378static void Write_protocol_list_t_TypeDecl(std::string &Result,
5379 long super_protocol_count) {
5380 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5381 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5382 Result += "\tstruct _protocol_t *super_protocols[";
5383 Result += utostr(super_protocol_count); Result += "];\n";
5384 Result += "}";
5385}
5386
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005387static void Write_method_list_t_TypeDecl(std::string &Result,
5388 unsigned int method_count) {
5389 Result += "struct /*_method_list_t*/"; Result += " {\n";
5390 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5391 Result += "\tunsigned int method_count;\n";
5392 Result += "\tstruct _objc_method method_list[";
5393 Result += utostr(method_count); Result += "];\n";
5394 Result += "}";
5395}
5396
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005397static void Write__prop_list_t_TypeDecl(std::string &Result,
5398 unsigned int property_count) {
5399 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5400 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5401 Result += "\tunsigned int count_of_properties;\n";
5402 Result += "\tstruct _prop_t prop_list[";
5403 Result += utostr(property_count); Result += "];\n";
5404 Result += "}";
5405}
5406
Fariborz Jahanianae932952012-02-10 20:47:10 +00005407static void Write__ivar_list_t_TypeDecl(std::string &Result,
5408 unsigned int ivar_count) {
5409 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5410 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5411 Result += "\tunsigned int count;\n";
5412 Result += "\tstruct _ivar_t ivar_list[";
5413 Result += utostr(ivar_count); Result += "];\n";
5414 Result += "}";
5415}
5416
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005417static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5418 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5419 StringRef VarName,
5420 StringRef ProtocolName) {
5421 if (SuperProtocols.size() > 0) {
5422 Result += "\nstatic ";
5423 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5424 Result += " "; Result += VarName;
5425 Result += ProtocolName;
5426 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5427 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5428 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5429 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5430 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5431 Result += SuperPD->getNameAsString();
5432 if (i == e-1)
5433 Result += "\n};\n";
5434 else
5435 Result += ",\n";
5436 }
5437 }
5438}
5439
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005440static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5441 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005442 ArrayRef<ObjCMethodDecl *> Methods,
5443 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005444 StringRef TopLevelDeclName,
5445 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005446 if (Methods.size() > 0) {
5447 Result += "\nstatic ";
5448 Write_method_list_t_TypeDecl(Result, Methods.size());
5449 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005450 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005451 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5452 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5453 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5454 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5455 ObjCMethodDecl *MD = Methods[i];
5456 if (i == 0)
5457 Result += "\t{{(struct objc_selector *)\"";
5458 else
5459 Result += "\t{(struct objc_selector *)\"";
5460 Result += (MD)->getSelector().getAsString(); Result += "\"";
5461 Result += ", ";
5462 std::string MethodTypeString;
5463 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5464 Result += "\""; Result += MethodTypeString; Result += "\"";
5465 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005466 if (!MethodImpl)
5467 Result += "0";
5468 else {
5469 Result += "(void *)";
5470 Result += RewriteObj.MethodInternalNames[MD];
5471 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005472 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005473 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005474 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005475 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005476 }
5477 Result += "};\n";
5478 }
5479}
5480
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005481static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005482 ASTContext *Context, std::string &Result,
5483 ArrayRef<ObjCPropertyDecl *> Properties,
5484 const Decl *Container,
5485 StringRef VarName,
5486 StringRef ProtocolName) {
5487 if (Properties.size() > 0) {
5488 Result += "\nstatic ";
5489 Write__prop_list_t_TypeDecl(Result, Properties.size());
5490 Result += " "; Result += VarName;
5491 Result += ProtocolName;
5492 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5493 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5494 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5495 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5496 ObjCPropertyDecl *PropDecl = Properties[i];
5497 if (i == 0)
5498 Result += "\t{{\"";
5499 else
5500 Result += "\t{\"";
5501 Result += PropDecl->getName(); Result += "\",";
5502 std::string PropertyTypeString, QuotePropertyTypeString;
5503 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5504 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5505 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5506 if (i == e-1)
5507 Result += "}}\n";
5508 else
5509 Result += "},\n";
5510 }
5511 Result += "};\n";
5512 }
5513}
5514
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005515// Metadata flags
5516enum MetaDataDlags {
5517 CLS = 0x0,
5518 CLS_META = 0x1,
5519 CLS_ROOT = 0x2,
5520 OBJC2_CLS_HIDDEN = 0x10,
5521 CLS_EXCEPTION = 0x20,
5522
5523 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5524 CLS_HAS_IVAR_RELEASER = 0x40,
5525 /// class was compiled with -fobjc-arr
5526 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5527};
5528
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005529static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5530 unsigned int flags,
5531 const std::string &InstanceStart,
5532 const std::string &InstanceSize,
5533 ArrayRef<ObjCMethodDecl *>baseMethods,
5534 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5535 ArrayRef<ObjCIvarDecl *>ivars,
5536 ArrayRef<ObjCPropertyDecl *>Properties,
5537 StringRef VarName,
5538 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005539 Result += "\nstatic struct _class_ro_t ";
5540 Result += VarName; Result += ClassName;
5541 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5542 Result += "\t";
5543 Result += llvm::utostr(flags); Result += ", ";
5544 Result += InstanceStart; Result += ", ";
5545 Result += InstanceSize; Result += ", \n";
5546 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005547 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5548 if (Triple.getArch() == llvm::Triple::x86_64)
5549 // uint32_t const reserved; // only when building for 64bit targets
5550 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005551 // const uint8_t * const ivarLayout;
5552 Result += "0, \n\t";
5553 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005554 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005555 if (baseMethods.size() > 0) {
5556 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005557 if (metaclass)
5558 Result += "_OBJC_$_CLASS_METHODS_";
5559 else
5560 Result += "_OBJC_$_INSTANCE_METHODS_";
5561 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005562 Result += ",\n\t";
5563 }
5564 else
5565 Result += "0, \n\t";
5566
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005567 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005568 Result += "(const struct _objc_protocol_list *)&";
5569 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5570 Result += ",\n\t";
5571 }
5572 else
5573 Result += "0, \n\t";
5574
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005575 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005576 Result += "(const struct _ivar_list_t *)&";
5577 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5578 Result += ",\n\t";
5579 }
5580 else
5581 Result += "0, \n\t";
5582
5583 // weakIvarLayout
5584 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005585 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005586 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005587 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005588 Result += ",\n";
5589 }
5590 else
5591 Result += "0, \n";
5592
5593 Result += "};\n";
5594}
5595
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005596static void Write_class_t(ASTContext *Context, std::string &Result,
5597 StringRef VarName,
5598 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005599
5600 if (metadata && !CDecl->getSuperClass()) {
5601 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005602 Result += "\n";
5603 if (CDecl->getImplementation())
5604 Result += "__declspec(dllexport) ";
5605 Result += "extern struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005606 Result += CDecl->getNameAsString();
5607 Result += ";\n";
5608 }
5609 // Also, for possibility of 'super' metadata class not having been defined yet.
5610 if (CDecl->getSuperClass()) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005611 Result += "\n";
5612 if (CDecl->getSuperClass()->getImplementation())
5613 Result += "__declspec(dllexport) ";
5614 Result += "extern struct _class_t ";
5615 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005616 Result += CDecl->getSuperClass()->getNameAsString();
5617 Result += ";\n";
5618 }
5619
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005620 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005621 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5622 Result += "\t";
5623 if (metadata) {
5624 if (CDecl->getSuperClass()) {
5625 Result += "&"; Result += VarName;
5626 Result += CDecl->getSuperClass()->getNameAsString();
5627 Result += ",\n\t";
5628 Result += "&"; Result += VarName;
5629 Result += CDecl->getSuperClass()->getNameAsString();
5630 Result += ",\n\t";
5631 }
5632 else {
5633 Result += "&"; Result += VarName;
5634 Result += CDecl->getNameAsString();
5635 Result += ",\n\t";
5636 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5637 Result += ",\n\t";
5638 }
5639 }
5640 else {
5641 Result += "&OBJC_METACLASS_$_";
5642 Result += CDecl->getNameAsString();
5643 Result += ",\n\t";
5644 if (CDecl->getSuperClass()) {
5645 Result += "&"; Result += VarName;
5646 Result += CDecl->getSuperClass()->getNameAsString();
5647 Result += ",\n\t";
5648 }
5649 else
5650 Result += "0,\n\t";
5651 }
5652 Result += "(void *)&_objc_empty_cache,\n\t";
5653 Result += "(void *)&_objc_empty_vtable,\n\t";
5654 if (metadata)
5655 Result += "&_OBJC_METACLASS_RO_$_";
5656 else
5657 Result += "&_OBJC_CLASS_RO_$_";
5658 Result += CDecl->getNameAsString();
5659 Result += ",\n};\n";
5660}
5661
Fariborz Jahanian61186122012-02-17 18:40:41 +00005662static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5663 std::string &Result,
5664 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005665 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005666 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5667 ArrayRef<ObjCMethodDecl *> ClassMethods,
5668 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5669 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005670
5671 StringRef ClassName = ClassDecl->getNameAsString();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005672 // must declare an extern class object in case this class is not implemented
5673 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005674 Result += "\n";
5675 if (ClassDecl->getImplementation())
5676 Result += "__declspec(dllexport) ";
5677
5678 Result += "extern struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005679 Result += "OBJC_CLASS_$_"; Result += ClassName;
5680 Result += ";\n";
5681
Fariborz Jahanian61186122012-02-17 18:40:41 +00005682 Result += "\nstatic struct _category_t ";
5683 Result += "_OBJC_$_CATEGORY_";
5684 Result += ClassName; Result += "_$_"; Result += CatName;
5685 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5686 Result += "{\n";
5687 Result += "\t\""; Result += ClassName; Result += "\",\n";
5688 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5689 Result += ",\n";
5690 if (InstanceMethods.size() > 0) {
5691 Result += "\t(const struct _method_list_t *)&";
5692 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5693 Result += ClassName; Result += "_$_"; Result += CatName;
5694 Result += ",\n";
5695 }
5696 else
5697 Result += "\t0,\n";
5698
5699 if (ClassMethods.size() > 0) {
5700 Result += "\t(const struct _method_list_t *)&";
5701 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5702 Result += ClassName; Result += "_$_"; Result += CatName;
5703 Result += ",\n";
5704 }
5705 else
5706 Result += "\t0,\n";
5707
5708 if (RefedProtocols.size() > 0) {
5709 Result += "\t(const struct _protocol_list_t *)&";
5710 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5711 Result += ClassName; Result += "_$_"; Result += CatName;
5712 Result += ",\n";
5713 }
5714 else
5715 Result += "\t0,\n";
5716
5717 if (ClassProperties.size() > 0) {
5718 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5719 Result += ClassName; Result += "_$_"; Result += CatName;
5720 Result += ",\n";
5721 }
5722 else
5723 Result += "\t0,\n";
5724
5725 Result += "};\n";
5726}
5727
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005728static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5729 ASTContext *Context, std::string &Result,
5730 ArrayRef<ObjCMethodDecl *> Methods,
5731 StringRef VarName,
5732 StringRef ProtocolName) {
5733 if (Methods.size() == 0)
5734 return;
5735
5736 Result += "\nstatic const char *";
5737 Result += VarName; Result += ProtocolName;
5738 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5739 Result += "{\n";
5740 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5741 ObjCMethodDecl *MD = Methods[i];
5742 std::string MethodTypeString, QuoteMethodTypeString;
5743 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5744 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5745 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5746 if (i == e-1)
5747 Result += "\n};\n";
5748 else {
5749 Result += ",\n";
5750 }
5751 }
5752}
5753
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005754static void Write_IvarOffsetVar(ASTContext *Context,
5755 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005756 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005757 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005758 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5759 // this is what happens:
5760 /**
5761 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5762 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5763 Class->getVisibility() == HiddenVisibility)
5764 Visibility shoud be: HiddenVisibility;
5765 else
5766 Visibility shoud be: DefaultVisibility;
5767 */
5768
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005769 Result += "\n";
5770 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5771 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005772 if (Context->getLangOpts().MicrosoftExt)
5773 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5774
5775 if (!Context->getLangOpts().MicrosoftExt ||
5776 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005777 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005778 Result += "unsigned long int ";
5779 else
5780 Result += "__declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005781 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005782 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5783 Result += " = ";
5784 if (IvarDecl->isBitField()) {
5785 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5786 // place all bitfields at offset 0.
5787 Result += "0;\n";
5788 }
5789 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005790 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005791 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005792 Result += "_IMPL, ";
5793 Result += IvarDecl->getName(); Result += ");\n";
5794 }
5795 }
5796}
5797
Fariborz Jahanianae932952012-02-10 20:47:10 +00005798static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5799 ASTContext *Context, std::string &Result,
5800 ArrayRef<ObjCIvarDecl *> Ivars,
5801 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005802 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00005803 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005804 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005805
Fariborz Jahanianae932952012-02-10 20:47:10 +00005806 Result += "\nstatic ";
5807 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5808 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005809 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00005810 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5811 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5812 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5813 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5814 ObjCIvarDecl *IvarDecl = Ivars[i];
5815 if (i == 0)
5816 Result += "\t{{";
5817 else
5818 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005819 Result += "(unsigned long int *)&";
5820 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005821 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005822
5823 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5824 std::string IvarTypeString, QuoteIvarTypeString;
5825 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5826 IvarDecl);
5827 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5828 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5829
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005830 // FIXME. this alignment represents the host alignment and need be changed to
5831 // represent the target alignment.
5832 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5833 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005834 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005835 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5836 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005837 if (i == e-1)
5838 Result += "}}\n";
5839 else
5840 Result += "},\n";
5841 }
5842 Result += "};\n";
5843 }
5844}
5845
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005846/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005847void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5848 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005849
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005850 // Do not synthesize the protocol more than once.
5851 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5852 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005853 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005854
5855 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5856 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005857 // Must write out all protocol definitions in current qualifier list,
5858 // and in their nested qualifiers before writing out current definition.
5859 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5860 E = PDecl->protocol_end(); I != E; ++I)
5861 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005862
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005863 // Construct method lists.
5864 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5865 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5866 for (ObjCProtocolDecl::instmeth_iterator
5867 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5868 I != E; ++I) {
5869 ObjCMethodDecl *MD = *I;
5870 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5871 OptInstanceMethods.push_back(MD);
5872 } else {
5873 InstanceMethods.push_back(MD);
5874 }
5875 }
5876
5877 for (ObjCProtocolDecl::classmeth_iterator
5878 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5879 I != E; ++I) {
5880 ObjCMethodDecl *MD = *I;
5881 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5882 OptClassMethods.push_back(MD);
5883 } else {
5884 ClassMethods.push_back(MD);
5885 }
5886 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005887 std::vector<ObjCMethodDecl *> AllMethods;
5888 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5889 AllMethods.push_back(InstanceMethods[i]);
5890 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5891 AllMethods.push_back(ClassMethods[i]);
5892 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5893 AllMethods.push_back(OptInstanceMethods[i]);
5894 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5895 AllMethods.push_back(OptClassMethods[i]);
5896
5897 Write__extendedMethodTypes_initializer(*this, Context, Result,
5898 AllMethods,
5899 "_OBJC_PROTOCOL_METHOD_TYPES_",
5900 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005901 // Protocol's super protocol list
5902 std::vector<ObjCProtocolDecl *> SuperProtocols;
5903 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5904 E = PDecl->protocol_end(); I != E; ++I)
5905 SuperProtocols.push_back(*I);
5906
5907 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5908 "_OBJC_PROTOCOL_REFS_",
5909 PDecl->getNameAsString());
5910
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005911 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005912 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005913 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005914
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005915 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005916 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005917 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005918
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005919 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005920 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005921 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005922
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005923 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005924 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005925 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005926
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005927 // Protocol's property metadata.
5928 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5929 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5930 E = PDecl->prop_end(); I != E; ++I)
5931 ProtocolProperties.push_back(*I);
5932
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005933 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005934 /* Container */0,
5935 "_OBJC_PROTOCOL_PROPERTIES_",
5936 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005937
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005938 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005939 Result += "\n";
5940 if (LangOpts.MicrosoftExt)
5941 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005942 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005943 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005944 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5945 Result += "\t0,\n"; // id is; is null
5946 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005947 if (SuperProtocols.size() > 0) {
5948 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5949 Result += PDecl->getNameAsString(); Result += ",\n";
5950 }
5951 else
5952 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005953 if (InstanceMethods.size() > 0) {
5954 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5955 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005956 }
5957 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005958 Result += "\t0,\n";
5959
5960 if (ClassMethods.size() > 0) {
5961 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5962 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005963 }
5964 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005965 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005966
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005967 if (OptInstanceMethods.size() > 0) {
5968 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
5969 Result += PDecl->getNameAsString(); Result += ",\n";
5970 }
5971 else
5972 Result += "\t0,\n";
5973
5974 if (OptClassMethods.size() > 0) {
5975 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
5976 Result += PDecl->getNameAsString(); Result += ",\n";
5977 }
5978 else
5979 Result += "\t0,\n";
5980
5981 if (ProtocolProperties.size() > 0) {
5982 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
5983 Result += PDecl->getNameAsString(); Result += ",\n";
5984 }
5985 else
5986 Result += "\t0,\n";
5987
5988 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
5989 Result += "\t0,\n";
5990
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005991 if (AllMethods.size() > 0) {
5992 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
5993 Result += PDecl->getNameAsString();
5994 Result += "\n};\n";
5995 }
5996 else
5997 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005998
5999 // Use this protocol meta-data to build protocol list table in section
6000 // .objc_protolist$B
6001 // Unspecified visibility means 'private extern'.
6002 if (LangOpts.MicrosoftExt)
6003 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6004 Result += "struct _protocol_t *";
6005 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6006 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6007 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006008
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006009 // Mark this protocol as having been generated.
6010 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6011 llvm_unreachable("protocol already synthesized");
6012
6013}
6014
6015void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6016 const ObjCList<ObjCProtocolDecl> &Protocols,
6017 StringRef prefix, StringRef ClassName,
6018 std::string &Result) {
6019 if (Protocols.empty()) return;
6020
6021 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006022 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006023
6024 // Output the top lovel protocol meta-data for the class.
6025 /* struct _objc_protocol_list {
6026 struct _objc_protocol_list *next;
6027 int protocol_count;
6028 struct _objc_protocol *class_protocols[];
6029 }
6030 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006031 Result += "\n";
6032 if (LangOpts.MicrosoftExt)
6033 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6034 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006035 Result += "\tstruct _objc_protocol_list *next;\n";
6036 Result += "\tint protocol_count;\n";
6037 Result += "\tstruct _objc_protocol *class_protocols[";
6038 Result += utostr(Protocols.size());
6039 Result += "];\n} _OBJC_";
6040 Result += prefix;
6041 Result += "_PROTOCOLS_";
6042 Result += ClassName;
6043 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6044 "{\n\t0, ";
6045 Result += utostr(Protocols.size());
6046 Result += "\n";
6047
6048 Result += "\t,{&_OBJC_PROTOCOL_";
6049 Result += Protocols[0]->getNameAsString();
6050 Result += " \n";
6051
6052 for (unsigned i = 1; i != Protocols.size(); i++) {
6053 Result += "\t ,&_OBJC_PROTOCOL_";
6054 Result += Protocols[i]->getNameAsString();
6055 Result += "\n";
6056 }
6057 Result += "\t }\n};\n";
6058}
6059
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006060/// hasObjCExceptionAttribute - Return true if this class or any super
6061/// class has the __objc_exception__ attribute.
6062/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6063static bool hasObjCExceptionAttribute(ASTContext &Context,
6064 const ObjCInterfaceDecl *OID) {
6065 if (OID->hasAttr<ObjCExceptionAttr>())
6066 return true;
6067 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6068 return hasObjCExceptionAttribute(Context, Super);
6069 return false;
6070}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006071
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006072void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6073 std::string &Result) {
6074 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6075
6076 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006077 if (CDecl->isImplicitInterfaceDecl())
6078 assert(false &&
6079 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006080
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006081 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006082 SmallVector<ObjCIvarDecl *, 8> IVars;
6083
6084 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6085 IVD; IVD = IVD->getNextIvar()) {
6086 // Ignore unnamed bit-fields.
6087 if (!IVD->getDeclName())
6088 continue;
6089 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006090 }
6091
Fariborz Jahanianae932952012-02-10 20:47:10 +00006092 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006093 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006094 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006095
6096 // Build _objc_method_list for class's instance methods if needed
6097 SmallVector<ObjCMethodDecl *, 32>
6098 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6099
6100 // If any of our property implementations have associated getters or
6101 // setters, produce metadata for them as well.
6102 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6103 PropEnd = IDecl->propimpl_end();
6104 Prop != PropEnd; ++Prop) {
6105 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6106 continue;
6107 if (!(*Prop)->getPropertyIvarDecl())
6108 continue;
6109 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6110 if (!PD)
6111 continue;
6112 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6113 if (!Getter->isDefined())
6114 InstanceMethods.push_back(Getter);
6115 if (PD->isReadOnly())
6116 continue;
6117 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6118 if (!Setter->isDefined())
6119 InstanceMethods.push_back(Setter);
6120 }
6121
6122 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6123 "_OBJC_$_INSTANCE_METHODS_",
6124 IDecl->getNameAsString(), true);
6125
6126 SmallVector<ObjCMethodDecl *, 32>
6127 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6128
6129 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6130 "_OBJC_$_CLASS_METHODS_",
6131 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006132
6133 // Protocols referenced in class declaration?
6134 // Protocol's super protocol list
6135 std::vector<ObjCProtocolDecl *> RefedProtocols;
6136 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6137 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6138 E = Protocols.end();
6139 I != E; ++I) {
6140 RefedProtocols.push_back(*I);
6141 // Must write out all protocol definitions in current qualifier list,
6142 // and in their nested qualifiers before writing out current definition.
6143 RewriteObjCProtocolMetaData(*I, Result);
6144 }
6145
6146 Write_protocol_list_initializer(Context, Result,
6147 RefedProtocols,
6148 "_OBJC_CLASS_PROTOCOLS_$_",
6149 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006150
6151 // Protocol's property metadata.
6152 std::vector<ObjCPropertyDecl *> ClassProperties;
6153 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6154 E = CDecl->prop_end(); I != E; ++I)
6155 ClassProperties.push_back(*I);
6156
6157 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6158 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006159 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006160 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006161
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006162
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006163 // Data for initializing _class_ro_t metaclass meta-data
6164 uint32_t flags = CLS_META;
6165 std::string InstanceSize;
6166 std::string InstanceStart;
6167
6168
6169 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6170 if (classIsHidden)
6171 flags |= OBJC2_CLS_HIDDEN;
6172
6173 if (!CDecl->getSuperClass())
6174 // class is root
6175 flags |= CLS_ROOT;
6176 InstanceSize = "sizeof(struct _class_t)";
6177 InstanceStart = InstanceSize;
6178 Write__class_ro_t_initializer(Context, Result, flags,
6179 InstanceStart, InstanceSize,
6180 ClassMethods,
6181 0,
6182 0,
6183 0,
6184 "_OBJC_METACLASS_RO_$_",
6185 CDecl->getNameAsString());
6186
6187
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006188 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006189 flags = CLS;
6190 if (classIsHidden)
6191 flags |= OBJC2_CLS_HIDDEN;
6192
6193 if (hasObjCExceptionAttribute(*Context, CDecl))
6194 flags |= CLS_EXCEPTION;
6195
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006196 if (!CDecl->getSuperClass())
6197 // class is root
6198 flags |= CLS_ROOT;
6199
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006200 InstanceSize.clear();
6201 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006202 if (!ObjCSynthesizedStructs.count(CDecl)) {
6203 InstanceSize = "0";
6204 InstanceStart = "0";
6205 }
6206 else {
6207 InstanceSize = "sizeof(struct ";
6208 InstanceSize += CDecl->getNameAsString();
6209 InstanceSize += "_IMPL)";
6210
6211 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6212 if (IVD) {
6213 InstanceStart += "__OFFSETOFIVAR__(struct ";
6214 InstanceStart += CDecl->getNameAsString();
6215 InstanceStart += "_IMPL, ";
6216 InstanceStart += IVD->getNameAsString();
6217 InstanceStart += ")";
6218 }
6219 else
6220 InstanceStart = InstanceSize;
6221 }
6222 Write__class_ro_t_initializer(Context, Result, flags,
6223 InstanceStart, InstanceSize,
6224 InstanceMethods,
6225 RefedProtocols,
6226 IVars,
6227 ClassProperties,
6228 "_OBJC_CLASS_RO_$_",
6229 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006230
6231 Write_class_t(Context, Result,
6232 "OBJC_METACLASS_$_",
6233 CDecl, /*metaclass*/true);
6234
6235 Write_class_t(Context, Result,
6236 "OBJC_CLASS_$_",
6237 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006238
6239 if (ImplementationIsNonLazy(IDecl))
6240 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006241
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006242}
6243
6244void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6245 int ClsDefCount = ClassImplementation.size();
6246 int CatDefCount = CategoryImplementation.size();
6247
6248 // For each implemented class, write out all its meta data.
6249 for (int i = 0; i < ClsDefCount; i++)
6250 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6251
6252 // For each implemented category, write out all its meta data.
6253 for (int i = 0; i < CatDefCount; i++)
6254 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6255
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006256 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006257 if (LangOpts.MicrosoftExt)
6258 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006259 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6260 Result += llvm::utostr(ClsDefCount); Result += "]";
6261 Result +=
6262 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6263 "regular,no_dead_strip\")))= {\n";
6264 for (int i = 0; i < ClsDefCount; i++) {
6265 Result += "\t&OBJC_CLASS_$_";
6266 Result += ClassImplementation[i]->getNameAsString();
6267 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006268 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006269 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006270
6271 if (!DefinedNonLazyClasses.empty()) {
6272 if (LangOpts.MicrosoftExt)
6273 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6274 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6275 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6276 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6277 Result += ",\n";
6278 }
6279 Result += "};\n";
6280 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006281 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006282
6283 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006284 if (LangOpts.MicrosoftExt)
6285 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006286 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6287 Result += llvm::utostr(CatDefCount); Result += "]";
6288 Result +=
6289 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6290 "regular,no_dead_strip\")))= {\n";
6291 for (int i = 0; i < CatDefCount; i++) {
6292 Result += "\t&_OBJC_$_CATEGORY_";
6293 Result +=
6294 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6295 Result += "_$_";
6296 Result += CategoryImplementation[i]->getNameAsString();
6297 Result += ",\n";
6298 }
6299 Result += "};\n";
6300 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006301
6302 if (!DefinedNonLazyCategories.empty()) {
6303 if (LangOpts.MicrosoftExt)
6304 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6305 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6306 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6307 Result += "\t&_OBJC_$_CATEGORY_";
6308 Result +=
6309 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6310 Result += "_$_";
6311 Result += DefinedNonLazyCategories[i]->getNameAsString();
6312 Result += ",\n";
6313 }
6314 Result += "};\n";
6315 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006316}
6317
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006318void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6319 if (LangOpts.MicrosoftExt)
6320 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6321
6322 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6323 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006324 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006325}
6326
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006327/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6328/// implementation.
6329void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6330 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006331 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006332 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6333 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006334 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006335 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6336 CDecl = CDecl->getNextClassCategory())
6337 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6338 break;
6339
6340 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006341 FullCategoryName += "_$_";
6342 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006343
6344 // Build _objc_method_list for class's instance methods if needed
6345 SmallVector<ObjCMethodDecl *, 32>
6346 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6347
6348 // If any of our property implementations have associated getters or
6349 // setters, produce metadata for them as well.
6350 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6351 PropEnd = IDecl->propimpl_end();
6352 Prop != PropEnd; ++Prop) {
6353 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6354 continue;
6355 if (!(*Prop)->getPropertyIvarDecl())
6356 continue;
6357 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6358 if (!PD)
6359 continue;
6360 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6361 InstanceMethods.push_back(Getter);
6362 if (PD->isReadOnly())
6363 continue;
6364 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6365 InstanceMethods.push_back(Setter);
6366 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006367
Fariborz Jahanian61186122012-02-17 18:40:41 +00006368 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6369 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6370 FullCategoryName, true);
6371
6372 SmallVector<ObjCMethodDecl *, 32>
6373 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6374
6375 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6376 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6377 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006378
6379 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006380 // Protocol's super protocol list
6381 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006382 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6383 E = CDecl->protocol_end();
6384
6385 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006386 RefedProtocols.push_back(*I);
6387 // Must write out all protocol definitions in current qualifier list,
6388 // and in their nested qualifiers before writing out current definition.
6389 RewriteObjCProtocolMetaData(*I, Result);
6390 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006391
Fariborz Jahanian61186122012-02-17 18:40:41 +00006392 Write_protocol_list_initializer(Context, Result,
6393 RefedProtocols,
6394 "_OBJC_CATEGORY_PROTOCOLS_$_",
6395 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006396
Fariborz Jahanian61186122012-02-17 18:40:41 +00006397 // Protocol's property metadata.
6398 std::vector<ObjCPropertyDecl *> ClassProperties;
6399 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6400 E = CDecl->prop_end(); I != E; ++I)
6401 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006402
Fariborz Jahanian61186122012-02-17 18:40:41 +00006403 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6404 /* Container */0,
6405 "_OBJC_$_PROP_LIST_",
6406 FullCategoryName);
6407
6408 Write_category_t(*this, Context, Result,
6409 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006410 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006411 InstanceMethods,
6412 ClassMethods,
6413 RefedProtocols,
6414 ClassProperties);
6415
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006416 // Determine if this category is also "non-lazy".
6417 if (ImplementationIsNonLazy(IDecl))
6418 DefinedNonLazyCategories.push_back(CDecl);
6419
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006420}
6421
6422// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6423/// class methods.
6424template<typename MethodIterator>
6425void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6426 MethodIterator MethodEnd,
6427 bool IsInstanceMethod,
6428 StringRef prefix,
6429 StringRef ClassName,
6430 std::string &Result) {
6431 if (MethodBegin == MethodEnd) return;
6432
6433 if (!objc_impl_method) {
6434 /* struct _objc_method {
6435 SEL _cmd;
6436 char *method_types;
6437 void *_imp;
6438 }
6439 */
6440 Result += "\nstruct _objc_method {\n";
6441 Result += "\tSEL _cmd;\n";
6442 Result += "\tchar *method_types;\n";
6443 Result += "\tvoid *_imp;\n";
6444 Result += "};\n";
6445
6446 objc_impl_method = true;
6447 }
6448
6449 // Build _objc_method_list for class's methods if needed
6450
6451 /* struct {
6452 struct _objc_method_list *next_method;
6453 int method_count;
6454 struct _objc_method method_list[];
6455 }
6456 */
6457 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006458 Result += "\n";
6459 if (LangOpts.MicrosoftExt) {
6460 if (IsInstanceMethod)
6461 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6462 else
6463 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6464 }
6465 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006466 Result += "\tstruct _objc_method_list *next_method;\n";
6467 Result += "\tint method_count;\n";
6468 Result += "\tstruct _objc_method method_list[";
6469 Result += utostr(NumMethods);
6470 Result += "];\n} _OBJC_";
6471 Result += prefix;
6472 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6473 Result += "_METHODS_";
6474 Result += ClassName;
6475 Result += " __attribute__ ((used, section (\"__OBJC, __";
6476 Result += IsInstanceMethod ? "inst" : "cls";
6477 Result += "_meth\")))= ";
6478 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6479
6480 Result += "\t,{{(SEL)\"";
6481 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6482 std::string MethodTypeString;
6483 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6484 Result += "\", \"";
6485 Result += MethodTypeString;
6486 Result += "\", (void *)";
6487 Result += MethodInternalNames[*MethodBegin];
6488 Result += "}\n";
6489 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6490 Result += "\t ,{(SEL)\"";
6491 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6492 std::string MethodTypeString;
6493 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6494 Result += "\", \"";
6495 Result += MethodTypeString;
6496 Result += "\", (void *)";
6497 Result += MethodInternalNames[*MethodBegin];
6498 Result += "}\n";
6499 }
6500 Result += "\t }\n};\n";
6501}
6502
6503Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6504 SourceRange OldRange = IV->getSourceRange();
6505 Expr *BaseExpr = IV->getBase();
6506
6507 // Rewrite the base, but without actually doing replaces.
6508 {
6509 DisableReplaceStmtScope S(*this);
6510 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6511 IV->setBase(BaseExpr);
6512 }
6513
6514 ObjCIvarDecl *D = IV->getDecl();
6515
6516 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006517
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006518 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6519 const ObjCInterfaceType *iFaceDecl =
6520 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6521 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6522 // lookup which class implements the instance variable.
6523 ObjCInterfaceDecl *clsDeclared = 0;
6524 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6525 clsDeclared);
6526 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6527
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006528 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006529 std::string IvarOffsetName;
6530 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
6531
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006532 ReferencedIvars[clsDeclared].insert(D);
6533
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006534 // cast offset to "char *".
6535 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6536 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006537 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006538 BaseExpr);
6539 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6540 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6541 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006542 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6543 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006544 SourceLocation());
6545 BinaryOperator *addExpr =
6546 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6547 Context->getPointerType(Context->CharTy),
6548 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006549 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006550 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6551 SourceLocation(),
6552 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006553 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006554 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006555 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006556
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006557 castExpr = NoTypeInfoCStyleCastExpr(Context,
6558 castT,
6559 CK_BitCast,
6560 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006561 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006562 VK_LValue, OK_Ordinary,
6563 SourceLocation());
6564 PE = new (Context) ParenExpr(OldRange.getBegin(),
6565 OldRange.getEnd(),
6566 Exp);
6567
6568 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006569 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006570
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006571 ReplaceStmtWithRange(IV, Replacement, OldRange);
6572 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006573}