1 //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Hacks and fun related to the code rewriter.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Rewrite/Frontend/ASTConsumers.h"
15 #include "clang/Rewrite/Core/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"
30 using namespace clang;
34 class RewriteModernObjC : public ASTConsumer {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
47 BLOCK_BYREF_CURRENT_MAX = 256
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)
58 static const int OBJC_ABI_VERSION = 7;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
65 TranslationUnitDecl *TUDecl;
67 const char *MainFileStart, *MainFileEnd;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 Expr *GlobalConstructionExp;
77 unsigned RewriteFailedDiag;
78 unsigned GlobalBlockRewriteFailedDiag;
79 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
84 // ObjC foreach break/continue generation support.
87 unsigned TryFinallyContainsReturnDiag;
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
106 /* Misc. containers needed for meta-data rewrite. */
107 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
109 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
110 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
112 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
113 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
114 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
115 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
117 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
118 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
120 SmallVector<Stmt *, 32> Stmts;
121 SmallVector<int, 8> ObjCBcLabelNo;
122 // Remember all the @protocol(<expr>) expressions.
123 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
125 llvm::DenseSet<uint64_t> CopyDestroyCache;
127 // Block expressions.
128 SmallVector<BlockExpr *, 32> Blocks;
129 SmallVector<int, 32> InnerDeclRefsCount;
130 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
132 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
134 // Block related declarations.
135 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
136 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
137 SmallVector<ValueDecl *, 8> BlockByRefDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
139 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
140 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
141 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
143 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
144 llvm::DenseMap<ObjCInterfaceDecl *,
145 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
152 // Needed for header files being rewritten
154 bool SilenceRewriteMacroWarning;
155 bool objc_impl_method;
157 bool DisableReplaceStmt;
158 class DisableReplaceStmtScope {
159 RewriteModernObjC &R;
163 DisableReplaceStmtScope(RewriteModernObjC &R)
164 : R(R), SavedValue(R.DisableReplaceStmt) {
165 R.DisableReplaceStmt = true;
167 ~DisableReplaceStmtScope() {
168 R.DisableReplaceStmt = SavedValue;
171 void InitializeCommon(ASTContext &context);
174 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
175 // Top Level Driver code.
176 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
177 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
179 if (!Class->isThisDeclarationADefinition()) {
180 RewriteForwardClassDecl(D);
183 // Keep track of all interface declarations seen.
184 ObjCInterfacesSeen.push_back(Class);
189 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
190 if (!Proto->isThisDeclarationADefinition()) {
191 RewriteForwardProtocolDecl(D);
196 HandleTopLevelSingleDecl(*I);
200 void HandleTopLevelSingleDecl(Decl *D);
201 void HandleDeclInMainFile(Decl *D);
202 RewriteModernObjC(std::string inFile, raw_ostream *OS,
203 DiagnosticsEngine &D, const LangOptions &LOpts,
204 bool silenceMacroWarn);
206 ~RewriteModernObjC() {}
208 virtual void HandleTranslationUnit(ASTContext &C);
210 void ReplaceStmt(Stmt *Old, Stmt *New) {
211 Stmt *ReplacingStmt = ReplacedNodes[Old];
214 return; // We can't rewrite the same node twice.
216 if (DisableReplaceStmt)
219 // If replacement succeeded or warning disabled return with no warning.
220 if (!Rewrite.ReplaceStmt(Old, New)) {
221 ReplacedNodes[Old] = New;
224 if (SilenceRewriteMacroWarning)
226 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227 << Old->getSourceRange();
230 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
231 if (DisableReplaceStmt)
234 // Measure the old text.
235 int Size = Rewrite.getRangeSize(SrcRange);
237 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238 << Old->getSourceRange();
243 llvm::raw_string_ostream S(SStr);
244 New->printPretty(S, 0, PrintingPolicy(LangOpts));
245 const std::string &Str = S.str();
247 // If replacement succeeded or warning disabled return with no warning.
248 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
249 ReplacedNodes[Old] = New;
252 if (SilenceRewriteMacroWarning)
254 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
255 << Old->getSourceRange();
258 void InsertText(SourceLocation Loc, StringRef Str,
259 bool InsertAfter = true) {
260 // If insertion succeeded or warning disabled return with no warning.
261 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
262 SilenceRewriteMacroWarning)
265 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
268 void ReplaceText(SourceLocation Start, unsigned OrigLength,
270 // If removal succeeded or warning disabled return with no warning.
271 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
272 SilenceRewriteMacroWarning)
275 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
278 // Syntactic Rewriting.
279 void RewriteRecordBody(RecordDecl *RD);
280 void RewriteInclude();
281 void RewriteLineDirective(const Decl *D);
282 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
283 std::string &LineString);
284 void RewriteForwardClassDecl(DeclGroupRef D);
285 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
286 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
287 const std::string &typedefString);
288 void RewriteImplementations();
289 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
290 ObjCImplementationDecl *IMD,
291 ObjCCategoryImplDecl *CID);
292 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
293 void RewriteImplementationDecl(Decl *Dcl);
294 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
295 ObjCMethodDecl *MDecl, std::string &ResultStr);
296 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
297 const FunctionType *&FPRetType);
298 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
299 ValueDecl *VD, bool def=false);
300 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
301 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
302 void RewriteForwardProtocolDecl(DeclGroupRef D);
303 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
304 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
305 void RewriteProperty(ObjCPropertyDecl *prop);
306 void RewriteFunctionDecl(FunctionDecl *FD);
307 void RewriteBlockPointerType(std::string& Str, QualType Type);
308 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
309 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
310 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
311 void RewriteTypeOfDecl(VarDecl *VD);
312 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
314 std::string getIvarAccessString(ObjCIvarDecl *D);
316 // Expression Rewriting.
317 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
318 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
319 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
320 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
321 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
322 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
323 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
324 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
325 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
326 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
327 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
328 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
329 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
330 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
331 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
332 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
333 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
334 SourceLocation OrigEnd);
335 Stmt *RewriteBreakStmt(BreakStmt *S);
336 Stmt *RewriteContinueStmt(ContinueStmt *S);
337 void RewriteCastExpr(CStyleCastExpr *CE);
338 void RewriteImplicitCastObjCExpr(CastExpr *IE);
339 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
342 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
344 // Block specific rewrite rules.
345 void RewriteBlockPointerDecl(NamedDecl *VD);
346 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
347 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
348 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
349 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
351 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
352 std::string &Result);
354 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
355 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
356 bool &IsNamedDefinition);
357 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
358 std::string &Result);
360 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
362 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
363 std::string &Result);
365 virtual void Initialize(ASTContext &context);
367 // Misc. AST transformation routines. Sometimes they end up calling
368 // rewriting routines on the new ASTs.
369 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
370 Expr **args, unsigned nargs,
371 SourceLocation StartLoc=SourceLocation(),
372 SourceLocation EndLoc=SourceLocation());
374 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
375 QualType msgSendType,
377 SmallVectorImpl<QualType> &ArgTypes,
378 SmallVectorImpl<Expr*> &MsgExprs,
379 ObjCMethodDecl *Method);
381 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
382 SourceLocation StartLoc=SourceLocation(),
383 SourceLocation EndLoc=SourceLocation());
385 void SynthCountByEnumWithState(std::string &buf);
386 void SynthMsgSendFunctionDecl();
387 void SynthMsgSendSuperFunctionDecl();
388 void SynthMsgSendStretFunctionDecl();
389 void SynthMsgSendFpretFunctionDecl();
390 void SynthMsgSendSuperStretFunctionDecl();
391 void SynthGetClassFunctionDecl();
392 void SynthGetMetaClassFunctionDecl();
393 void SynthGetSuperClassFunctionDecl();
394 void SynthSelGetUidFunctionDecl();
395 void SynthSuperContructorFunctionDecl();
397 // Rewriting metadata
398 template<typename MethodIterator>
399 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
400 MethodIterator MethodEnd,
401 bool IsInstanceMethod,
404 std::string &Result);
405 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
406 std::string &Result);
407 void RewriteObjCProtocolListMetaData(
408 const ObjCList<ObjCProtocolDecl> &Prots,
409 StringRef prefix, StringRef ClassName, std::string &Result);
410 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
411 std::string &Result);
412 void RewriteClassSetupInitHook(std::string &Result);
414 void RewriteMetaDataIntoBuffer(std::string &Result);
415 void WriteImageInfo(std::string &Result);
416 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
417 std::string &Result);
418 void RewriteCategorySetupInitHook(std::string &Result);
421 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
422 std::string &Result);
423 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
426 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
427 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
428 StringRef funcName, std::string Tag);
429 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
430 StringRef funcName, std::string Tag);
431 std::string SynthesizeBlockImpl(BlockExpr *CE,
432 std::string Tag, std::string Desc);
433 std::string SynthesizeBlockDescriptor(std::string DescTag,
435 int i, StringRef funcName,
437 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
438 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
440 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
441 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
442 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
444 // Misc. helper routines.
445 QualType getProtocolType();
446 void WarnAboutReturnGotoStmts(Stmt *S);
447 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
448 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
449 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
451 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
452 void CollectBlockDeclRefInfo(BlockExpr *Exp);
453 void GetBlockDeclRefExprs(Stmt *S);
454 void GetInnerBlockDeclRefExprs(Stmt *S,
455 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
456 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
458 // We avoid calling Type::isBlockPointerType(), since it operates on the
459 // canonical type. We only care if the top-level type is a closure pointer.
460 bool isTopLevelBlockPointerType(QualType T) {
461 return isa<BlockPointerType>(T);
464 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
465 /// to a function pointer type and upon success, returns true; false
467 bool convertBlockPointerToFunctionPointer(QualType &T) {
468 if (isTopLevelBlockPointerType(T)) {
469 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
470 T = Context->getPointerType(BPT->getPointeeType());
476 bool convertObjCTypeToCStyleType(QualType &T);
478 bool needToScanForQualifiers(QualType T);
479 QualType getSuperStructType();
480 QualType getConstantStringStructType();
481 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
482 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
484 void convertToUnqualifiedObjCType(QualType &T) {
485 if (T->isObjCQualifiedIdType()) {
486 bool isConst = T.isConstQualified();
487 T = isConst ? Context->getObjCIdType().withConst()
488 : Context->getObjCIdType();
490 else if (T->isObjCQualifiedClassType())
491 T = Context->getObjCClassType();
492 else if (T->isObjCObjectPointerType() &&
493 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
494 if (const ObjCObjectPointerType * OBJPT =
495 T->getAsObjCInterfacePointerType()) {
496 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
497 T = QualType(IFaceT, 0);
498 T = Context->getPointerType(T);
503 // FIXME: This predicate seems like it would be useful to add to ASTContext.
504 bool isObjCType(QualType T) {
505 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
508 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
510 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
511 OCT == Context->getCanonicalType(Context->getObjCClassType()))
514 if (const PointerType *PT = OCT->getAs<PointerType>()) {
515 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
516 PT->getPointeeType()->isObjCQualifiedIdType())
521 bool PointerTypeTakesAnyBlockArguments(QualType QT);
522 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
523 void GetExtentOfArgList(const char *Name, const char *&LParen,
524 const char *&RParen);
526 void QuoteDoublequotes(std::string &From, std::string &To) {
527 for (unsigned i = 0; i < From.length(); i++) {
535 QualType getSimpleFunctionType(QualType result,
536 const QualType *args,
538 bool variadic = false) {
539 if (result == Context->getObjCInstanceType())
540 result = Context->getObjCIdType();
541 FunctionProtoType::ExtProtoInfo fpi;
542 fpi.Variadic = variadic;
543 return Context->getFunctionType(result, args, numArgs, fpi);
546 // Helper function: create a CStyleCastExpr with trivial type source info.
547 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
548 CastKind Kind, Expr *E) {
549 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
550 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
551 SourceLocation(), SourceLocation());
554 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
555 IdentifierInfo* II = &Context->Idents.get("load");
556 Selector LoadSel = Context->Selectors.getSelector(0, &II);
557 return OD->getClassMethod(LoadSel) != 0;
563 void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
565 if (const FunctionProtoType *fproto
566 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
567 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
568 E = fproto->arg_type_end(); I && (I != E); ++I)
569 if (isTopLevelBlockPointerType(*I)) {
570 // All the args are checked/rewritten. Don't call twice!
571 RewriteBlockPointerDecl(D);
577 void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
578 const PointerType *PT = funcType->getAs<PointerType>();
579 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
580 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
583 static bool IsHeaderFile(const std::string &Filename) {
584 std::string::size_type DotPos = Filename.rfind('.');
586 if (DotPos == std::string::npos) {
591 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
593 // C++ header: .hh or .H;
594 return Ext == "h" || Ext == "hh" || Ext == "H";
597 RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
598 DiagnosticsEngine &D, const LangOptions &LOpts,
599 bool silenceMacroWarn)
600 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
601 SilenceRewriteMacroWarning(silenceMacroWarn) {
602 IsHeader = IsHeaderFile(inFile);
603 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
604 "rewriting sub-expression within a macro (may not be correct)");
605 // FIXME. This should be an error. But if block is not called, it is OK. And it
606 // may break including some headers.
607 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
608 "rewriting block literal declared in global scope is not implemented");
610 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
611 DiagnosticsEngine::Warning,
612 "rewriter doesn't support user-specified control flow semantics "
613 "for @try/@finally (code may not execute properly)");
616 ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
618 DiagnosticsEngine &Diags,
619 const LangOptions &LOpts,
620 bool SilenceRewriteMacroWarning) {
621 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
624 void RewriteModernObjC::InitializeCommon(ASTContext &context) {
626 SM = &Context->getSourceManager();
627 TUDecl = Context->getTranslationUnitDecl();
628 MsgSendFunctionDecl = 0;
629 MsgSendSuperFunctionDecl = 0;
630 MsgSendStretFunctionDecl = 0;
631 MsgSendSuperStretFunctionDecl = 0;
632 MsgSendFpretFunctionDecl = 0;
633 GetClassFunctionDecl = 0;
634 GetMetaClassFunctionDecl = 0;
635 GetSuperClassFunctionDecl = 0;
636 SelGetUidFunctionDecl = 0;
637 CFStringFunctionDecl = 0;
638 ConstantStringClassReference = 0;
643 GlobalConstructionExp = 0;
645 ProtocolTypeDecl = 0;
646 ConstantStringDecl = 0;
648 SuperContructorFunctionDecl = 0;
649 NumObjCStringLiterals = 0;
652 DisableReplaceStmt = false;
653 objc_impl_method = false;
655 // Get the ID and start/end of the main file.
656 MainFileID = SM->getMainFileID();
657 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
658 MainFileStart = MainBuf->getBufferStart();
659 MainFileEnd = MainBuf->getBufferEnd();
661 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
664 //===----------------------------------------------------------------------===//
665 // Top Level Driver Code
666 //===----------------------------------------------------------------------===//
668 void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
669 if (Diags.hasErrorOccurred())
672 // Two cases: either the decl could be in the main file, or it could be in a
673 // #included file. If the former, rewrite it now. If the later, check to see
674 // if we rewrote the #include/#import.
675 SourceLocation Loc = D->getLocation();
676 Loc = SM->getExpansionLoc(Loc);
678 // If this is for a builtin, ignore it.
679 if (Loc.isInvalid()) return;
681 // Look for built-in declarations that we need to refer during the rewrite.
682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
683 RewriteFunctionDecl(FD);
684 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
685 // declared in <Foundation/NSString.h>
686 if (FVD->getName() == "_NSConstantStringClassReference") {
687 ConstantStringClassReference = FVD;
690 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
691 RewriteCategoryDecl(CD);
692 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
693 if (PD->isThisDeclarationADefinition())
694 RewriteProtocolDecl(PD);
695 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
696 // FIXME. This will not work in all situations and leaving it out
698 // RewriteLinkageSpec(LSD);
700 // Recurse into linkage specifications
701 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
702 DIEnd = LSD->decls_end();
704 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
705 if (!IFace->isThisDeclarationADefinition()) {
706 SmallVector<Decl *, 8> DG;
707 SourceLocation StartLoc = IFace->getLocStart();
709 if (isa<ObjCInterfaceDecl>(*DI) &&
710 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
711 StartLoc == (*DI)->getLocStart())
717 } while (DI != DIEnd);
718 RewriteForwardClassDecl(DG);
722 // Keep track of all interface declarations seen.
723 ObjCInterfacesSeen.push_back(IFace);
729 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
730 if (!Proto->isThisDeclarationADefinition()) {
731 SmallVector<Decl *, 8> DG;
732 SourceLocation StartLoc = Proto->getLocStart();
734 if (isa<ObjCProtocolDecl>(*DI) &&
735 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
736 StartLoc == (*DI)->getLocStart())
742 } while (DI != DIEnd);
743 RewriteForwardProtocolDecl(DG);
748 HandleTopLevelSingleDecl(*DI);
752 // If we have a decl in the main file, see if we should rewrite it.
753 if (SM->isFromMainFile(Loc))
754 return HandleDeclInMainFile(D);
757 //===----------------------------------------------------------------------===//
758 // Syntactic (non-AST) Rewriting Code
759 //===----------------------------------------------------------------------===//
761 void RewriteModernObjC::RewriteInclude() {
762 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
763 StringRef MainBuf = SM->getBufferData(MainFileID);
764 const char *MainBufStart = MainBuf.begin();
765 const char *MainBufEnd = MainBuf.end();
766 size_t ImportLen = strlen("import");
768 // Loop over the whole file, looking for includes.
769 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
770 if (*BufPtr == '#') {
771 if (++BufPtr == MainBufEnd)
773 while (*BufPtr == ' ' || *BufPtr == '\t')
774 if (++BufPtr == MainBufEnd)
776 if (!strncmp(BufPtr, "import", ImportLen)) {
777 // replace import with include
778 SourceLocation ImportLoc =
779 LocStart.getLocWithOffset(BufPtr-MainBufStart);
780 ReplaceText(ImportLoc, ImportLen, "include");
787 static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
788 ObjCIvarDecl *IvarDecl, std::string &Result) {
789 Result += "OBJC_IVAR_$_";
790 Result += IDecl->getName();
792 Result += IvarDecl->getName();
796 RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
797 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
799 // Build name of symbol holding ivar offset.
800 std::string IvarOffsetName;
801 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
804 std::string S = "(*(";
805 QualType IvarT = D->getType();
807 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
808 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
809 RD = RD->getDefinition();
810 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
811 // decltype(((Foo_IMPL*)0)->bar) *
812 ObjCContainerDecl *CDecl =
813 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
814 // ivar in class extensions requires special treatment.
815 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
816 CDecl = CatDecl->getClassInterface();
817 std::string RecName = CDecl->getName();
819 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
820 SourceLocation(), SourceLocation(),
821 &Context->Idents.get(RecName.c_str()));
822 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
823 unsigned UnsignedIntSize =
824 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
825 Expr *Zero = IntegerLiteral::Create(*Context,
826 llvm::APInt(UnsignedIntSize, 0),
827 Context->UnsignedIntTy, SourceLocation());
828 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
829 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
831 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
833 &Context->Idents.get(D->getNameAsString()),
835 /*BitWidth=*/0, /*Mutable=*/true,
837 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
838 FD->getType(), VK_LValue,
840 IvarT = Context->getDecltypeType(ME, ME->getType());
843 convertObjCTypeToCStyleType(IvarT);
844 QualType castT = Context->getPointerType(IvarT);
845 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
849 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
850 S += "((char *)self + ";
853 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
857 /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
858 /// been found in the class implementation. In this case, it must be synthesized.
859 static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
860 ObjCPropertyDecl *PD,
862 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
863 : !IMP->getInstanceMethod(PD->getSetterName());
867 void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
868 ObjCImplementationDecl *IMD,
869 ObjCCategoryImplDecl *CID) {
870 static bool objcGetPropertyDefined = false;
871 static bool objcSetPropertyDefined = false;
872 SourceLocation startGetterSetterLoc;
874 if (PID->getLocStart().isValid()) {
875 SourceLocation startLoc = PID->getLocStart();
876 InsertText(startLoc, "// ");
877 const char *startBuf = SM->getCharacterData(startLoc);
878 assert((*startBuf == '@') && "bogus @synthesize location");
879 const char *semiBuf = strchr(startBuf, ';');
880 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
881 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
884 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
886 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
887 return; // FIXME: is this correct?
889 // Generate the 'getter' function.
890 ObjCPropertyDecl *PD = PID->getPropertyDecl();
891 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
895 unsigned Attributes = PD->getPropertyAttributes();
896 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
897 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
898 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
899 ObjCPropertyDecl::OBJC_PR_copy));
901 if (GenGetProperty && !objcGetPropertyDefined) {
902 objcGetPropertyDefined = true;
903 // FIXME. Is this attribute correct in all cases?
904 Getr = "\nextern \"C\" __declspec(dllimport) "
905 "id objc_getProperty(id, SEL, long, bool);\n";
907 RewriteObjCMethodDecl(OID->getContainingInterface(),
908 PD->getGetterMethodDecl(), Getr);
910 // Synthesize an explicit cast to gain access to the ivar.
911 // See objc-act.c:objc_synthesize_new_getter() for details.
912 if (GenGetProperty) {
913 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
915 const FunctionType *FPRetType = 0;
916 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
920 Getr += ")"; // close the precedence "scope" for "*".
922 // Now, emit the argument types (if any).
923 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
925 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
927 std::string ParamStr = FT->getArgType(i).getAsString(
928 Context->getPrintingPolicy());
931 if (FT->isVariadic()) {
932 if (FT->getNumArgs()) Getr += ", ";
940 Getr += "return (_TYPE)";
941 Getr += "objc_getProperty(self, _cmd, ";
942 RewriteIvarOffsetComputation(OID, Getr);
946 Getr += "return " + getIvarAccessString(OID);
948 InsertText(startGetterSetterLoc, Getr);
951 if (PD->isReadOnly() ||
952 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
955 // Generate the 'setter' function.
957 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
958 ObjCPropertyDecl::OBJC_PR_copy);
959 if (GenSetProperty && !objcSetPropertyDefined) {
960 objcSetPropertyDefined = true;
961 // FIXME. Is this attribute correct in all cases?
962 Setr = "\nextern \"C\" __declspec(dllimport) "
963 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
966 RewriteObjCMethodDecl(OID->getContainingInterface(),
967 PD->getSetterMethodDecl(), Setr);
969 // Synthesize an explicit cast to initialize the ivar.
970 // See objc-act.c:objc_synthesize_new_setter() for details.
971 if (GenSetProperty) {
972 Setr += "objc_setProperty (self, _cmd, ";
973 RewriteIvarOffsetComputation(OID, Setr);
975 Setr += PD->getName();
977 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
981 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
987 Setr += getIvarAccessString(OID) + " = ";
988 Setr += PD->getName();
991 InsertText(startGetterSetterLoc, Setr);
994 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
995 std::string &typedefString) {
996 typedefString += "#ifndef _REWRITER_typedef_";
997 typedefString += ForwardDecl->getNameAsString();
998 typedefString += "\n";
999 typedefString += "#define _REWRITER_typedef_";
1000 typedefString += ForwardDecl->getNameAsString();
1001 typedefString += "\n";
1002 typedefString += "typedef struct objc_object ";
1003 typedefString += ForwardDecl->getNameAsString();
1004 // typedef struct { } _objc_exc_Classname;
1005 typedefString += ";\ntypedef struct {} _objc_exc_";
1006 typedefString += ForwardDecl->getNameAsString();
1007 typedefString += ";\n#endif\n";
1010 void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1011 const std::string &typedefString) {
1012 SourceLocation startLoc = ClassDecl->getLocStart();
1013 const char *startBuf = SM->getCharacterData(startLoc);
1014 const char *semiPtr = strchr(startBuf, ';');
1015 // Replace the @class with typedefs corresponding to the classes.
1016 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1019 void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1020 std::string typedefString;
1021 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1022 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1023 if (I == D.begin()) {
1024 // Translate to typedef's that forward reference structs with the same name
1025 // as the class. As a convenience, we include the original declaration
1027 typedefString += "// @class ";
1028 typedefString += ForwardDecl->getNameAsString();
1029 typedefString += ";\n";
1031 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1033 DeclGroupRef::iterator I = D.begin();
1034 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1037 void RewriteModernObjC::RewriteForwardClassDecl(
1038 const llvm::SmallVector<Decl*, 8> &D) {
1039 std::string typedefString;
1040 for (unsigned i = 0; i < D.size(); i++) {
1041 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1043 typedefString += "// @class ";
1044 typedefString += ForwardDecl->getNameAsString();
1045 typedefString += ";\n";
1047 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1049 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1052 void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1053 // When method is a synthesized one, such as a getter/setter there is
1054 // nothing to rewrite.
1055 if (Method->isImplicit())
1057 SourceLocation LocStart = Method->getLocStart();
1058 SourceLocation LocEnd = Method->getLocEnd();
1060 if (SM->getExpansionLineNumber(LocEnd) >
1061 SM->getExpansionLineNumber(LocStart)) {
1062 InsertText(LocStart, "#if 0\n");
1063 ReplaceText(LocEnd, 1, ";\n#endif\n");
1065 InsertText(LocStart, "// ");
1069 void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1070 SourceLocation Loc = prop->getAtLoc();
1072 ReplaceText(Loc, 0, "// ");
1073 // FIXME: handle properties that are declared across multiple lines.
1076 void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1077 SourceLocation LocStart = CatDecl->getLocStart();
1079 // FIXME: handle category headers that are declared across multiple lines.
1080 if (CatDecl->getIvarRBraceLoc().isValid()) {
1081 ReplaceText(LocStart, 1, "/** ");
1082 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1085 ReplaceText(LocStart, 0, "// ");
1088 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1089 E = CatDecl->prop_end(); I != E; ++I)
1090 RewriteProperty(*I);
1092 for (ObjCCategoryDecl::instmeth_iterator
1093 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1095 RewriteMethodDeclaration(*I);
1096 for (ObjCCategoryDecl::classmeth_iterator
1097 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1099 RewriteMethodDeclaration(*I);
1101 // Lastly, comment out the @end.
1102 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1103 strlen("@end"), "/* @end */");
1106 void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1107 SourceLocation LocStart = PDecl->getLocStart();
1108 assert(PDecl->isThisDeclarationADefinition());
1110 // FIXME: handle protocol headers that are declared across multiple lines.
1111 ReplaceText(LocStart, 0, "// ");
1113 for (ObjCProtocolDecl::instmeth_iterator
1114 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1116 RewriteMethodDeclaration(*I);
1117 for (ObjCProtocolDecl::classmeth_iterator
1118 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1120 RewriteMethodDeclaration(*I);
1122 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1123 E = PDecl->prop_end(); I != E; ++I)
1124 RewriteProperty(*I);
1126 // Lastly, comment out the @end.
1127 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1128 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1130 // Must comment out @optional/@required
1131 const char *startBuf = SM->getCharacterData(LocStart);
1132 const char *endBuf = SM->getCharacterData(LocEnd);
1133 for (const char *p = startBuf; p < endBuf; p++) {
1134 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1135 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1136 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1139 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1140 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1141 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1147 void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1148 SourceLocation LocStart = (*D.begin())->getLocStart();
1149 if (LocStart.isInvalid())
1150 llvm_unreachable("Invalid SourceLocation");
1151 // FIXME: handle forward protocol that are declared across multiple lines.
1152 ReplaceText(LocStart, 0, "// ");
1156 RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1157 SourceLocation LocStart = DG[0]->getLocStart();
1158 if (LocStart.isInvalid())
1159 llvm_unreachable("Invalid SourceLocation");
1160 // FIXME: handle forward protocol that are declared across multiple lines.
1161 ReplaceText(LocStart, 0, "// ");
1165 RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1166 SourceLocation LocStart = LSD->getExternLoc();
1167 if (LocStart.isInvalid())
1168 llvm_unreachable("Invalid extern SourceLocation");
1170 ReplaceText(LocStart, 0, "// ");
1171 if (!LSD->hasBraces())
1173 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1174 SourceLocation LocRBrace = LSD->getRBraceLoc();
1175 if (LocRBrace.isInvalid())
1176 llvm_unreachable("Invalid rbrace SourceLocation");
1177 ReplaceText(LocRBrace, 0, "// ");
1180 void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1181 const FunctionType *&FPRetType) {
1182 if (T->isObjCQualifiedIdType())
1184 else if (T->isFunctionPointerType() ||
1185 T->isBlockPointerType()) {
1186 // needs special handling, since pointer-to-functions have special
1187 // syntax (where a decaration models use).
1188 QualType retType = T;
1190 if (const PointerType* PT = retType->getAs<PointerType>())
1191 PointeeTy = PT->getPointeeType();
1192 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1193 PointeeTy = BPT->getPointeeType();
1194 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1195 ResultStr += FPRetType->getResultType().getAsString(
1196 Context->getPrintingPolicy());
1200 ResultStr += T.getAsString(Context->getPrintingPolicy());
1203 void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1204 ObjCMethodDecl *OMD,
1205 std::string &ResultStr) {
1206 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1207 const FunctionType *FPRetType = 0;
1208 ResultStr += "\nstatic ";
1209 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1212 // Unique method name
1213 std::string NameStr;
1215 if (OMD->isInstanceMethod())
1220 NameStr += IDecl->getNameAsString();
1223 if (ObjCCategoryImplDecl *CID =
1224 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1225 NameStr += CID->getNameAsString();
1228 // Append selector names, replacing ':' with '_'
1230 std::string selString = OMD->getSelector().getAsString();
1231 int len = selString.size();
1232 for (int i = 0; i < len; i++)
1233 if (selString[i] == ':')
1235 NameStr += selString;
1237 // Remember this name for metadata emission
1238 MethodInternalNames[OMD] = NameStr;
1239 ResultStr += NameStr;
1241 // Rewrite arguments
1244 // invisible arguments
1245 if (OMD->isInstanceMethod()) {
1246 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1247 selfTy = Context->getPointerType(selfTy);
1248 if (!LangOpts.MicrosoftExt) {
1249 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1250 ResultStr += "struct ";
1252 // When rewriting for Microsoft, explicitly omit the structure name.
1253 ResultStr += IDecl->getNameAsString();
1257 ResultStr += Context->getObjCClassType().getAsString(
1258 Context->getPrintingPolicy());
1260 ResultStr += " self, ";
1261 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1262 ResultStr += " _cmd";
1264 // Method arguments.
1265 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1266 E = OMD->param_end(); PI != E; ++PI) {
1267 ParmVarDecl *PDecl = *PI;
1269 if (PDecl->getType()->isObjCQualifiedIdType()) {
1271 ResultStr += PDecl->getNameAsString();
1273 std::string Name = PDecl->getNameAsString();
1274 QualType QT = PDecl->getType();
1275 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1276 (void)convertBlockPointerToFunctionPointer(QT);
1277 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1281 if (OMD->isVariadic())
1282 ResultStr += ", ...";
1286 ResultStr += ")"; // close the precedence "scope" for "*".
1288 // Now, emit the argument types (if any).
1289 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1291 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1292 if (i) ResultStr += ", ";
1293 std::string ParamStr = FT->getArgType(i).getAsString(
1294 Context->getPrintingPolicy());
1295 ResultStr += ParamStr;
1297 if (FT->isVariadic()) {
1298 if (FT->getNumArgs()) ResultStr += ", ";
1307 void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1308 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1309 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1312 if (IMD->getIvarRBraceLoc().isValid()) {
1313 ReplaceText(IMD->getLocStart(), 1, "/** ");
1314 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1317 InsertText(IMD->getLocStart(), "// ");
1321 InsertText(CID->getLocStart(), "// ");
1323 for (ObjCCategoryImplDecl::instmeth_iterator
1324 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1325 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1327 std::string ResultStr;
1328 ObjCMethodDecl *OMD = *I;
1329 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1330 SourceLocation LocStart = OMD->getLocStart();
1331 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1333 const char *startBuf = SM->getCharacterData(LocStart);
1334 const char *endBuf = SM->getCharacterData(LocEnd);
1335 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1338 for (ObjCCategoryImplDecl::classmeth_iterator
1339 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1340 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1342 std::string ResultStr;
1343 ObjCMethodDecl *OMD = *I;
1344 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1345 SourceLocation LocStart = OMD->getLocStart();
1346 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1348 const char *startBuf = SM->getCharacterData(LocStart);
1349 const char *endBuf = SM->getCharacterData(LocEnd);
1350 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1352 for (ObjCCategoryImplDecl::propimpl_iterator
1353 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1354 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1356 RewritePropertyImplDecl(*I, IMD, CID);
1359 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1362 void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1363 // Do not synthesize more than once.
1364 if (ObjCSynthesizedStructs.count(ClassDecl))
1366 // Make sure super class's are written before current class is written.
1367 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1368 while (SuperClass) {
1369 RewriteInterfaceDecl(SuperClass);
1370 SuperClass = SuperClass->getSuperClass();
1372 std::string ResultStr;
1373 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1374 // we haven't seen a forward decl - generate a typedef.
1375 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1376 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1378 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1379 // Mark this typedef as having been written into its c++ equivalent.
1380 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1382 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1383 E = ClassDecl->prop_end(); I != E; ++I)
1384 RewriteProperty(*I);
1385 for (ObjCInterfaceDecl::instmeth_iterator
1386 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
1388 RewriteMethodDeclaration(*I);
1389 for (ObjCInterfaceDecl::classmeth_iterator
1390 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
1392 RewriteMethodDeclaration(*I);
1394 // Lastly, comment out the @end.
1395 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1400 Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1401 SourceRange OldRange = PseudoOp->getSourceRange();
1403 // We just magically know some things about the structure of this
1405 ObjCMessageExpr *OldMsg =
1406 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1407 PseudoOp->getNumSemanticExprs() - 1));
1409 // Because the rewriter doesn't allow us to rewrite rewritten code,
1410 // we need to suppress rewriting the sub-statements.
1412 SmallVector<Expr*, 2> Args;
1414 DisableReplaceStmtScope S(*this);
1416 // Rebuild the base expression if we have one.
1418 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1419 Base = OldMsg->getInstanceReceiver();
1420 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1421 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1424 unsigned numArgs = OldMsg->getNumArgs();
1425 for (unsigned i = 0; i < numArgs; i++) {
1426 Expr *Arg = OldMsg->getArg(i);
1427 if (isa<OpaqueValueExpr>(Arg))
1428 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1429 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1430 Args.push_back(Arg);
1434 // TODO: avoid this copy.
1435 SmallVector<SourceLocation, 1> SelLocs;
1436 OldMsg->getSelectorLocs(SelLocs);
1438 ObjCMessageExpr *NewMsg = 0;
1439 switch (OldMsg->getReceiverKind()) {
1440 case ObjCMessageExpr::Class:
1441 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1442 OldMsg->getValueKind(),
1443 OldMsg->getLeftLoc(),
1444 OldMsg->getClassReceiverTypeInfo(),
1445 OldMsg->getSelector(),
1447 OldMsg->getMethodDecl(),
1449 OldMsg->getRightLoc(),
1450 OldMsg->isImplicit());
1453 case ObjCMessageExpr::Instance:
1454 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1455 OldMsg->getValueKind(),
1456 OldMsg->getLeftLoc(),
1458 OldMsg->getSelector(),
1460 OldMsg->getMethodDecl(),
1462 OldMsg->getRightLoc(),
1463 OldMsg->isImplicit());
1466 case ObjCMessageExpr::SuperClass:
1467 case ObjCMessageExpr::SuperInstance:
1468 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1469 OldMsg->getValueKind(),
1470 OldMsg->getLeftLoc(),
1471 OldMsg->getSuperLoc(),
1472 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1473 OldMsg->getSuperType(),
1474 OldMsg->getSelector(),
1476 OldMsg->getMethodDecl(),
1478 OldMsg->getRightLoc(),
1479 OldMsg->isImplicit());
1483 Stmt *Replacement = SynthMessageExpr(NewMsg);
1484 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1488 Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1489 SourceRange OldRange = PseudoOp->getSourceRange();
1491 // We just magically know some things about the structure of this
1493 ObjCMessageExpr *OldMsg =
1494 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1496 // Because the rewriter doesn't allow us to rewrite rewritten code,
1497 // we need to suppress rewriting the sub-statements.
1499 SmallVector<Expr*, 1> Args;
1501 DisableReplaceStmtScope S(*this);
1502 // Rebuild the base expression if we have one.
1503 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1504 Base = OldMsg->getInstanceReceiver();
1505 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1506 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1508 unsigned numArgs = OldMsg->getNumArgs();
1509 for (unsigned i = 0; i < numArgs; i++) {
1510 Expr *Arg = OldMsg->getArg(i);
1511 if (isa<OpaqueValueExpr>(Arg))
1512 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1513 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1514 Args.push_back(Arg);
1518 // Intentionally empty.
1519 SmallVector<SourceLocation, 1> SelLocs;
1521 ObjCMessageExpr *NewMsg = 0;
1522 switch (OldMsg->getReceiverKind()) {
1523 case ObjCMessageExpr::Class:
1524 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1525 OldMsg->getValueKind(),
1526 OldMsg->getLeftLoc(),
1527 OldMsg->getClassReceiverTypeInfo(),
1528 OldMsg->getSelector(),
1530 OldMsg->getMethodDecl(),
1532 OldMsg->getRightLoc(),
1533 OldMsg->isImplicit());
1536 case ObjCMessageExpr::Instance:
1537 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1538 OldMsg->getValueKind(),
1539 OldMsg->getLeftLoc(),
1541 OldMsg->getSelector(),
1543 OldMsg->getMethodDecl(),
1545 OldMsg->getRightLoc(),
1546 OldMsg->isImplicit());
1549 case ObjCMessageExpr::SuperClass:
1550 case ObjCMessageExpr::SuperInstance:
1551 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1552 OldMsg->getValueKind(),
1553 OldMsg->getLeftLoc(),
1554 OldMsg->getSuperLoc(),
1555 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1556 OldMsg->getSuperType(),
1557 OldMsg->getSelector(),
1559 OldMsg->getMethodDecl(),
1561 OldMsg->getRightLoc(),
1562 OldMsg->isImplicit());
1566 Stmt *Replacement = SynthMessageExpr(NewMsg);
1567 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1571 /// SynthCountByEnumWithState - To print:
1572 /// ((unsigned int (*)
1573 /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1574 /// (void *)objc_msgSend)((id)l_collection,
1575 /// sel_registerName(
1576 /// "countByEnumeratingWithState:objects:count:"),
1578 /// (id *)__rw_items, (unsigned int)16)
1580 void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1581 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1582 "id *, unsigned int))(void *)objc_msgSend)";
1584 buf += "((id)l_collection,\n\t\t";
1585 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1587 buf += "&enumState, "
1588 "(id *)__rw_items, (unsigned int)16)";
1591 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1592 /// statement to exit to its outer synthesized loop.
1594 Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1595 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1597 // replace break with goto __break_label
1600 SourceLocation startLoc = S->getLocStart();
1601 buf = "goto __break_label_";
1602 buf += utostr(ObjCBcLabelNo.back());
1603 ReplaceText(startLoc, strlen("break"), buf);
1608 void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1610 std::string &LineString) {
1611 if (Loc.isFileID()) {
1612 LineString += "\n#line ";
1613 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1614 LineString += utostr(PLoc.getLine());
1615 LineString += " \"";
1616 LineString += Lexer::Stringify(PLoc.getFilename());
1617 LineString += "\"\n";
1621 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1622 /// statement to continue with its inner synthesized loop.
1624 Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1625 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1627 // replace continue with goto __continue_label
1630 SourceLocation startLoc = S->getLocStart();
1631 buf = "goto __continue_label_";
1632 buf += utostr(ObjCBcLabelNo.back());
1633 ReplaceText(startLoc, strlen("continue"), buf);
1638 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1640 /// for ( type elem in collection) { stmts; }
1645 /// struct __objcFastEnumerationState enumState = { 0 };
1646 /// id __rw_items[16];
1647 /// id l_collection = (id)collection;
1648 /// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1649 /// objects:__rw_items count:16];
1651 /// unsigned long startMutations = *enumState.mutationsPtr;
1653 /// unsigned long counter = 0;
1655 /// if (startMutations != *enumState.mutationsPtr)
1656 /// objc_enumerationMutation(l_collection);
1657 /// elem = (type)enumState.itemsPtr[counter++];
1659 /// __continue_label: ;
1660 /// } while (counter < limit);
1661 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1662 /// objects:__rw_items count:16]);
1664 /// __break_label: ;
1670 Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1671 SourceLocation OrigEnd) {
1672 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1673 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1674 "ObjCForCollectionStmt Statement stack mismatch");
1675 assert(!ObjCBcLabelNo.empty() &&
1676 "ObjCForCollectionStmt - Label No stack empty");
1678 SourceLocation startLoc = S->getLocStart();
1679 const char *startBuf = SM->getCharacterData(startLoc);
1680 StringRef elementName;
1681 std::string elementTypeAsString;
1683 // line directive first.
1684 SourceLocation ForEachLoc = S->getForLoc();
1685 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1687 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1689 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1690 QualType ElementType = cast<ValueDecl>(D)->getType();
1691 if (ElementType->isObjCQualifiedIdType() ||
1692 ElementType->isObjCQualifiedInterfaceType())
1693 // Simply use 'id' for all qualified types.
1694 elementTypeAsString = "id";
1696 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1697 buf += elementTypeAsString;
1699 elementName = D->getName();
1704 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1705 elementName = DR->getDecl()->getName();
1706 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1707 if (VD->getType()->isObjCQualifiedIdType() ||
1708 VD->getType()->isObjCQualifiedInterfaceType())
1709 // Simply use 'id' for all qualified types.
1710 elementTypeAsString = "id";
1712 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1715 // struct __objcFastEnumerationState enumState = { 0 };
1716 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1717 // id __rw_items[16];
1718 buf += "id __rw_items[16];\n\t";
1719 // id l_collection = (id)
1720 buf += "id l_collection = (id)";
1721 // Find start location of 'collection' the hard way!
1722 const char *startCollectionBuf = startBuf;
1723 startCollectionBuf += 3; // skip 'for'
1724 startCollectionBuf = strchr(startCollectionBuf, '(');
1725 startCollectionBuf++; // skip '('
1726 // find 'in' and skip it.
1727 while (*startCollectionBuf != ' ' ||
1728 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1729 (*(startCollectionBuf+3) != ' ' &&
1730 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1731 startCollectionBuf++;
1732 startCollectionBuf += 3;
1734 // Replace: "for (type element in" with string constructed thus far.
1735 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1736 // Replace ')' in for '(' type elem in collection ')' with ';'
1737 SourceLocation rightParenLoc = S->getRParenLoc();
1738 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1739 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1742 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1743 // objects:__rw_items count:16];
1744 // which is synthesized into:
1745 // unsigned int limit =
1746 // ((unsigned int (*)
1747 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1748 // (void *)objc_msgSend)((id)l_collection,
1749 // sel_registerName(
1750 // "countByEnumeratingWithState:objects:count:"),
1751 // (struct __objcFastEnumerationState *)&state,
1752 // (id *)__rw_items, (unsigned int)16);
1753 buf += "unsigned long limit =\n\t\t";
1754 SynthCountByEnumWithState(buf);
1757 /// unsigned long startMutations = *enumState.mutationsPtr;
1759 /// unsigned long counter = 0;
1761 /// if (startMutations != *enumState.mutationsPtr)
1762 /// objc_enumerationMutation(l_collection);
1763 /// elem = (type)enumState.itemsPtr[counter++];
1764 buf += "if (limit) {\n\t";
1765 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1766 buf += "do {\n\t\t";
1767 buf += "unsigned long counter = 0;\n\t\t";
1768 buf += "do {\n\t\t\t";
1769 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1770 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1773 buf += elementTypeAsString;
1774 buf += ")enumState.itemsPtr[counter++];";
1775 // Replace ')' in for '(' type elem in collection ')' with all of these.
1776 ReplaceText(lparenLoc, 1, buf);
1778 /// __continue_label: ;
1779 /// } while (counter < limit);
1780 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1781 /// objects:__rw_items count:16]);
1783 /// __break_label: ;
1790 buf += "__continue_label_";
1791 buf += utostr(ObjCBcLabelNo.back());
1794 buf += "} while (counter < limit);\n\t";
1795 buf += "} while (limit = ";
1796 SynthCountByEnumWithState(buf);
1800 buf += elementTypeAsString;
1802 buf += "__break_label_";
1803 buf += utostr(ObjCBcLabelNo.back());
1806 buf += "else\n\t\t";
1809 buf += elementTypeAsString;
1813 // Insert all these *after* the statement body.
1814 // FIXME: If this should support Obj-C++, support CXXTryStmt
1815 if (isa<CompoundStmt>(S->getBody())) {
1816 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1817 InsertText(endBodyLoc, buf);
1819 /* Need to treat single statements specially. For example:
1821 * for (A *a in b) if (stuff()) break;
1822 * for (A *a in b) xxxyy;
1824 * The following code simply scans ahead to the semi to find the actual end.
1826 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1827 const char *semiBuf = strchr(stmtBuf, ';');
1828 assert(semiBuf && "Can't find ';'");
1829 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1830 InsertText(endBodyLoc, buf);
1833 ObjCBcLabelNo.pop_back();
1837 static void Write_RethrowObject(std::string &buf) {
1838 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1839 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1840 buf += "\tid rethrow;\n";
1841 buf += "\t} _fin_force_rethow(_rethrow);";
1844 /// RewriteObjCSynchronizedStmt -
1845 /// This routine rewrites @synchronized(expr) stmt;
1847 /// objc_sync_enter(expr);
1848 /// @try stmt @finally { objc_sync_exit(expr); }
1850 Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1851 // Get the start location and compute the semi location.
1852 SourceLocation startLoc = S->getLocStart();
1853 const char *startBuf = SM->getCharacterData(startLoc);
1855 assert((*startBuf == '@') && "bogus @synchronized location");
1858 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1859 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1860 buf += "{ id _rethrow = 0; id _sync_obj = ";
1862 const char *lparenBuf = startBuf;
1863 while (*lparenBuf != '(') lparenBuf++;
1864 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1866 buf = "; objc_sync_enter(_sync_obj);\n";
1867 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1868 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1869 buf += "\n\tid sync_exit;";
1870 buf += "\n\t} _sync_exit(_sync_obj);\n";
1872 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1873 // the sync expression is typically a message expression that's already
1874 // been rewritten! (which implies the SourceLocation's are invalid).
1875 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1876 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1877 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1878 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1880 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1881 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1882 assert (*LBraceLocBuf == '{');
1883 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1885 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
1886 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1887 "bogus @synchronized block");
1889 buf = "} catch (id e) {_rethrow = e;}\n";
1890 Write_RethrowObject(buf);
1894 ReplaceText(startRBraceLoc, 1, buf);
1899 void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1901 // Perform a bottom up traversal of all children.
1902 for (Stmt::child_range CI = S->children(); CI; ++CI)
1904 WarnAboutReturnGotoStmts(*CI);
1906 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1907 Diags.Report(Context->getFullLoc(S->getLocStart()),
1908 TryFinallyContainsReturnDiag);
1913 Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1914 SourceLocation startLoc = S->getAtLoc();
1915 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1916 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1917 "{ __AtAutoreleasePool __autoreleasepool; ");
1922 Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1923 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1924 bool noCatch = S->getNumCatchStmts() == 0;
1926 SourceLocation TryLocation = S->getAtTryLoc();
1927 ConvertSourceLocationToLineDirective(TryLocation, buf);
1931 buf += "{ id volatile _rethrow = 0;\n";
1933 buf += "{ id volatile _rethrow = 0;\ntry {\n";
1936 // Get the start location and compute the semi location.
1937 SourceLocation startLoc = S->getLocStart();
1938 const char *startBuf = SM->getCharacterData(startLoc);
1940 assert((*startBuf == '@') && "bogus @try location");
1942 ReplaceText(startLoc, 1, buf);
1945 ReplaceText(startLoc, 1, "");
1947 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1948 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1949 VarDecl *catchDecl = Catch->getCatchParamDecl();
1951 startLoc = Catch->getLocStart();
1952 bool AtRemoved = false;
1954 QualType t = catchDecl->getType();
1955 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1956 // Should be a pointer to a class.
1957 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1960 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1962 startBuf = SM->getCharacterData(startLoc);
1963 assert((*startBuf == '@') && "bogus @catch location");
1964 SourceLocation rParenLoc = Catch->getRParenLoc();
1965 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1967 // _objc_exc_Foo *_e as argument to catch.
1968 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1969 Result += " *_"; Result += catchDecl->getNameAsString();
1971 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1972 // Foo *e = (Foo *)_e;
1975 Result += IDecl->getNameAsString();
1976 Result += " *"; Result += catchDecl->getNameAsString();
1977 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1978 Result += "_"; Result += catchDecl->getNameAsString();
1981 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1982 ReplaceText(lBraceLoc, 1, Result);
1989 ReplaceText(startLoc, 1, "");
1994 SourceLocation FinallyLoc = finalStmt->getLocStart();
1997 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
1998 buf += "catch (id e) {_rethrow = e;}\n";
2002 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2003 buf += "catch (id e) {_rethrow = e;}\n";
2006 SourceLocation startFinalLoc = finalStmt->getLocStart();
2007 ReplaceText(startFinalLoc, 8, buf);
2008 Stmt *body = finalStmt->getFinallyBody();
2009 SourceLocation startFinalBodyLoc = body->getLocStart();
2011 Write_RethrowObject(buf);
2012 ReplaceText(startFinalBodyLoc, 1, buf);
2014 SourceLocation endFinalBodyLoc = body->getLocEnd();
2015 ReplaceText(endFinalBodyLoc, 1, "}\n}");
2016 // Now check for any return/continue/go statements within the @try.
2017 WarnAboutReturnGotoStmts(S->getTryBody());
2023 // This can't be done with ReplaceStmt(S, ThrowExpr), since
2024 // the throw expression is typically a message expression that's already
2025 // been rewritten! (which implies the SourceLocation's are invalid).
2026 Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2027 // Get the start location and compute the semi location.
2028 SourceLocation startLoc = S->getLocStart();
2029 const char *startBuf = SM->getCharacterData(startLoc);
2031 assert((*startBuf == '@') && "bogus @throw location");
2034 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2035 if (S->getThrowExpr())
2036 buf = "objc_exception_throw(";
2040 // handle "@ throw" correctly.
2041 const char *wBuf = strchr(startBuf, 'w');
2042 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2043 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2045 const char *semiBuf = strchr(startBuf, ';');
2046 assert((*semiBuf == ';') && "@throw: can't find ';'");
2047 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2048 if (S->getThrowExpr())
2049 ReplaceText(semiLoc, 1, ");");
2053 Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2054 // Create a new string expression.
2055 QualType StrType = Context->getPointerType(Context->CharTy);
2056 std::string StrEncoding;
2057 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2058 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2059 StringLiteral::Ascii, false,
2060 StrType, SourceLocation());
2061 ReplaceStmt(Exp, Replacement);
2063 // Replace this subexpr in the parent.
2064 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2068 Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2069 if (!SelGetUidFunctionDecl)
2070 SynthSelGetUidFunctionDecl();
2071 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2072 // Create a call to sel_registerName("selName").
2073 SmallVector<Expr*, 8> SelExprs;
2074 QualType argType = Context->getPointerType(Context->CharTy);
2075 SelExprs.push_back(StringLiteral::Create(*Context,
2076 Exp->getSelector().getAsString(),
2077 StringLiteral::Ascii, false,
2078 argType, SourceLocation()));
2079 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2080 &SelExprs[0], SelExprs.size());
2081 ReplaceStmt(Exp, SelExp);
2082 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2086 CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2087 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2088 SourceLocation EndLoc) {
2089 // Get the type, we will need to reference it in a couple spots.
2090 QualType msgSendType = FD->getType();
2092 // Create a reference to the objc_msgSend() declaration.
2094 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
2096 // Now, we cast the reference to a pointer to the objc_msgSend type.
2097 QualType pToFunc = Context->getPointerType(msgSendType);
2098 ImplicitCastExpr *ICE =
2099 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2102 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2105 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
2106 FT->getCallResultType(*Context),
2111 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2112 const char *&startRef, const char *&endRef) {
2113 while (startBuf < endBuf) {
2114 if (*startBuf == '<')
2115 startRef = startBuf; // mark the start.
2116 if (*startBuf == '>') {
2117 if (startRef && *startRef == '<') {
2118 endRef = startBuf; // mark the end.
2128 static void scanToNextArgument(const char *&argRef) {
2130 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2133 else if (*argRef == '>')
2137 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2140 bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2141 if (T->isObjCQualifiedIdType())
2143 if (const PointerType *PT = T->getAs<PointerType>()) {
2144 if (PT->getPointeeType()->isObjCQualifiedIdType())
2147 if (T->isObjCObjectPointerType()) {
2148 T = T->getPointeeType();
2149 return T->isObjCQualifiedInterfaceType();
2151 if (T->isArrayType()) {
2152 QualType ElemTy = Context->getBaseElementType(T);
2153 return needToScanForQualifiers(ElemTy);
2158 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2159 QualType Type = E->getType();
2160 if (needToScanForQualifiers(Type)) {
2161 SourceLocation Loc, EndLoc;
2163 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2164 Loc = ECE->getLParenLoc();
2165 EndLoc = ECE->getRParenLoc();
2167 Loc = E->getLocStart();
2168 EndLoc = E->getLocEnd();
2170 // This will defend against trying to rewrite synthesized expressions.
2171 if (Loc.isInvalid() || EndLoc.isInvalid())
2174 const char *startBuf = SM->getCharacterData(Loc);
2175 const char *endBuf = SM->getCharacterData(EndLoc);
2176 const char *startRef = 0, *endRef = 0;
2177 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2178 // Get the locations of the startRef, endRef.
2179 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2180 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2181 // Comment out the protocol references.
2182 InsertText(LessLoc, "/*");
2183 InsertText(GreaterLoc, "*/");
2188 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2191 const FunctionProtoType *proto = 0;
2192 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2193 Loc = VD->getLocation();
2194 Type = VD->getType();
2196 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2197 Loc = FD->getLocation();
2198 // Check for ObjC 'id' and class types that have been adorned with protocol
2199 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2200 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2201 assert(funcType && "missing function type");
2202 proto = dyn_cast<FunctionProtoType>(funcType);
2205 Type = proto->getResultType();
2207 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2208 Loc = FD->getLocation();
2209 Type = FD->getType();
2214 if (needToScanForQualifiers(Type)) {
2215 // Since types are unique, we need to scan the buffer.
2217 const char *endBuf = SM->getCharacterData(Loc);
2218 const char *startBuf = endBuf;
2219 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2220 startBuf--; // scan backward (from the decl location) for return type.
2221 const char *startRef = 0, *endRef = 0;
2222 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2223 // Get the locations of the startRef, endRef.
2224 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2225 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2226 // Comment out the protocol references.
2227 InsertText(LessLoc, "/*");
2228 InsertText(GreaterLoc, "*/");
2232 return; // most likely, was a variable
2233 // Now check arguments.
2234 const char *startBuf = SM->getCharacterData(Loc);
2235 const char *startFuncBuf = startBuf;
2236 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2237 if (needToScanForQualifiers(proto->getArgType(i))) {
2238 // Since types are unique, we need to scan the buffer.
2240 const char *endBuf = startBuf;
2241 // scan forward (from the decl location) for argument types.
2242 scanToNextArgument(endBuf);
2243 const char *startRef = 0, *endRef = 0;
2244 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2245 // Get the locations of the startRef, endRef.
2246 SourceLocation LessLoc =
2247 Loc.getLocWithOffset(startRef-startFuncBuf);
2248 SourceLocation GreaterLoc =
2249 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2250 // Comment out the protocol references.
2251 InsertText(LessLoc, "/*");
2252 InsertText(GreaterLoc, "*/");
2254 startBuf = ++endBuf;
2257 // If the function name is derived from a macro expansion, then the
2258 // argument buffer will not follow the name. Need to speak with Chris.
2259 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2260 startBuf++; // scan forward (from the decl location) for argument types.
2266 void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2267 QualType QT = ND->getType();
2268 const Type* TypePtr = QT->getAs<Type>();
2269 if (!isa<TypeOfExprType>(TypePtr))
2271 while (isa<TypeOfExprType>(TypePtr)) {
2272 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2273 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2274 TypePtr = QT->getAs<Type>();
2276 // FIXME. This will not work for multiple declarators; as in:
2277 // __typeof__(a) b,c,d;
2278 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2279 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2280 const char *startBuf = SM->getCharacterData(DeclLoc);
2281 if (ND->getInit()) {
2282 std::string Name(ND->getNameAsString());
2283 TypeAsString += " " + Name + " = ";
2284 Expr *E = ND->getInit();
2285 SourceLocation startLoc;
2286 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2287 startLoc = ECE->getLParenLoc();
2289 startLoc = E->getLocStart();
2290 startLoc = SM->getExpansionLoc(startLoc);
2291 const char *endBuf = SM->getCharacterData(startLoc);
2292 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2295 SourceLocation X = ND->getLocEnd();
2296 X = SM->getExpansionLoc(X);
2297 const char *endBuf = SM->getCharacterData(X);
2298 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2302 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2303 void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2304 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2305 SmallVector<QualType, 16> ArgTys;
2306 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2307 QualType getFuncType =
2308 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2309 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2312 SelGetUidIdent, getFuncType, 0,
2317 void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2318 // declared in <objc/objc.h>
2319 if (FD->getIdentifier() &&
2320 FD->getName() == "sel_registerName") {
2321 SelGetUidFunctionDecl = FD;
2324 RewriteObjCQualifiedInterfaceTypes(FD);
2327 void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2328 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2329 const char *argPtr = TypeString.c_str();
2330 if (!strchr(argPtr, '^')) {
2335 Str += (*argPtr == '^' ? '*' : *argPtr);
2340 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2341 void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2343 QualType Type = VD->getType();
2344 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2345 const char *argPtr = TypeString.c_str();
2360 Str += VD->getNameAsString();
2370 void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2371 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2372 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2373 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2376 QualType Type = proto->getResultType();
2377 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2379 FdStr += FD->getName();
2381 unsigned numArgs = proto->getNumArgs();
2382 for (unsigned i = 0; i < numArgs; i++) {
2383 QualType ArgType = proto->getArgType(i);
2384 RewriteBlockPointerType(FdStr, ArgType);
2388 if (FD->isVariadic()) {
2389 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2393 InsertText(FunLocStart, FdStr);
2396 // SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
2397 void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2398 if (SuperContructorFunctionDecl)
2400 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2401 SmallVector<QualType, 16> ArgTys;
2402 QualType argT = Context->getObjCIdType();
2403 assert(!argT.isNull() && "Can't find 'id' type");
2404 ArgTys.push_back(argT);
2405 ArgTys.push_back(argT);
2406 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2407 &ArgTys[0], ArgTys.size());
2408 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2411 msgSendIdent, msgSendType, 0,
2416 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2417 void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2418 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2419 SmallVector<QualType, 16> ArgTys;
2420 QualType argT = Context->getObjCIdType();
2421 assert(!argT.isNull() && "Can't find 'id' type");
2422 ArgTys.push_back(argT);
2423 argT = Context->getObjCSelType();
2424 assert(!argT.isNull() && "Can't find 'SEL' type");
2425 ArgTys.push_back(argT);
2426 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2427 &ArgTys[0], ArgTys.size(),
2428 true /*isVariadic*/);
2429 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2432 msgSendIdent, msgSendType, 0,
2437 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2438 void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2439 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2440 SmallVector<QualType, 2> ArgTys;
2441 ArgTys.push_back(Context->VoidTy);
2442 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2444 true /*isVariadic*/);
2445 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2448 msgSendIdent, msgSendType, 0,
2453 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2454 void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2455 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2456 SmallVector<QualType, 16> ArgTys;
2457 QualType argT = Context->getObjCIdType();
2458 assert(!argT.isNull() && "Can't find 'id' type");
2459 ArgTys.push_back(argT);
2460 argT = Context->getObjCSelType();
2461 assert(!argT.isNull() && "Can't find 'SEL' type");
2462 ArgTys.push_back(argT);
2463 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2464 &ArgTys[0], ArgTys.size(),
2465 true /*isVariadic*/);
2466 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2469 msgSendIdent, msgSendType, 0,
2474 // SynthMsgSendSuperStretFunctionDecl -
2475 // id objc_msgSendSuper_stret(void);
2476 void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2477 IdentifierInfo *msgSendIdent =
2478 &Context->Idents.get("objc_msgSendSuper_stret");
2479 SmallVector<QualType, 2> ArgTys;
2480 ArgTys.push_back(Context->VoidTy);
2481 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2483 true /*isVariadic*/);
2484 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2487 msgSendIdent, msgSendType, 0,
2492 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2493 void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2494 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2495 SmallVector<QualType, 16> ArgTys;
2496 QualType argT = Context->getObjCIdType();
2497 assert(!argT.isNull() && "Can't find 'id' type");
2498 ArgTys.push_back(argT);
2499 argT = Context->getObjCSelType();
2500 assert(!argT.isNull() && "Can't find 'SEL' type");
2501 ArgTys.push_back(argT);
2502 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2503 &ArgTys[0], ArgTys.size(),
2504 true /*isVariadic*/);
2505 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2508 msgSendIdent, msgSendType, 0,
2513 // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2514 void RewriteModernObjC::SynthGetClassFunctionDecl() {
2515 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2516 SmallVector<QualType, 16> ArgTys;
2517 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2518 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2519 &ArgTys[0], ArgTys.size());
2520 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2523 getClassIdent, getClassType, 0,
2528 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2529 void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2530 IdentifierInfo *getSuperClassIdent =
2531 &Context->Idents.get("class_getSuperclass");
2532 SmallVector<QualType, 16> ArgTys;
2533 ArgTys.push_back(Context->getObjCClassType());
2534 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2535 &ArgTys[0], ArgTys.size());
2536 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2546 // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2547 void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2548 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2549 SmallVector<QualType, 16> ArgTys;
2550 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2551 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2552 &ArgTys[0], ArgTys.size());
2553 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2556 getClassIdent, getClassType, 0,
2561 Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2562 QualType strType = getConstantStringStructType();
2564 std::string S = "__NSConstantStringImpl_";
2566 std::string tmpName = InFileName;
2568 for (i=0; i < tmpName.length(); i++) {
2569 char c = tmpName.at(i);
2570 // replace any non alphanumeric characters with '_'.
2571 if (!isalpha(c) && (c < '0' || c > '9'))
2576 S += utostr(NumObjCStringLiterals++);
2578 Preamble += "static __NSConstantStringImpl " + S;
2579 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2580 Preamble += "0x000007c8,"; // utf8_str
2581 // The pretty printer for StringLiteral handles escape characters properly.
2582 std::string prettyBufS;
2583 llvm::raw_string_ostream prettyBuf(prettyBufS);
2584 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
2585 Preamble += prettyBuf.str();
2587 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2589 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2590 SourceLocation(), &Context->Idents.get(S),
2591 strType, 0, SC_Static, SC_None);
2592 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2594 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2595 Context->getPointerType(DRE->getType()),
2596 VK_RValue, OK_Ordinary,
2598 // cast to NSConstantString *
2599 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2600 CK_CPointerToObjCPointerCast, Unop);
2601 ReplaceStmt(Exp, cast);
2602 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2606 Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2608 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2610 Expr *FlagExp = IntegerLiteral::Create(*Context,
2611 llvm::APInt(IntSize, Exp->getValue()),
2612 Context->IntTy, Exp->getLocation());
2613 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2614 CK_BitCast, FlagExp);
2615 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2617 ReplaceStmt(Exp, PE);
2621 Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2622 // synthesize declaration of helper functions needed in this routine.
2623 if (!SelGetUidFunctionDecl)
2624 SynthSelGetUidFunctionDecl();
2625 // use objc_msgSend() for all.
2626 if (!MsgSendFunctionDecl)
2627 SynthMsgSendFunctionDecl();
2628 if (!GetClassFunctionDecl)
2629 SynthGetClassFunctionDecl();
2631 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2632 SourceLocation StartLoc = Exp->getLocStart();
2633 SourceLocation EndLoc = Exp->getLocEnd();
2635 // Synthesize a call to objc_msgSend().
2636 SmallVector<Expr*, 4> MsgExprs;
2637 SmallVector<Expr*, 4> ClsExprs;
2638 QualType argType = Context->getPointerType(Context->CharTy);
2640 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2641 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2642 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2644 IdentifierInfo *clsName = BoxingClass->getIdentifier();
2645 ClsExprs.push_back(StringLiteral::Create(*Context,
2647 StringLiteral::Ascii, false,
2648 argType, SourceLocation()));
2649 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2653 MsgExprs.push_back(Cls);
2655 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2656 // it will be the 2nd argument.
2657 SmallVector<Expr*, 4> SelExprs;
2658 SelExprs.push_back(StringLiteral::Create(*Context,
2659 BoxingMethod->getSelector().getAsString(),
2660 StringLiteral::Ascii, false,
2661 argType, SourceLocation()));
2662 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2663 &SelExprs[0], SelExprs.size(),
2665 MsgExprs.push_back(SelExp);
2667 // User provided sub-expression is the 3rd, and last, argument.
2668 Expr *subExpr = Exp->getSubExpr();
2669 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2670 QualType type = ICE->getType();
2671 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2672 CastKind CK = CK_BitCast;
2673 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2674 CK = CK_IntegralToBoolean;
2675 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2677 MsgExprs.push_back(subExpr);
2679 SmallVector<QualType, 4> ArgTypes;
2680 ArgTypes.push_back(Context->getObjCIdType());
2681 ArgTypes.push_back(Context->getObjCSelType());
2682 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2683 E = BoxingMethod->param_end(); PI != E; ++PI)
2684 ArgTypes.push_back((*PI)->getType());
2686 QualType returnType = Exp->getType();
2687 // Get the type, we will need to reference it in a couple spots.
2688 QualType msgSendType = MsgSendFlavor->getType();
2690 // Create a reference to the objc_msgSend() declaration.
2691 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2692 VK_LValue, SourceLocation());
2694 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2695 Context->getPointerType(Context->VoidTy),
2698 // Now do the "normal" pointer to function cast.
2700 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2701 BoxingMethod->isVariadic());
2702 castType = Context->getPointerType(castType);
2703 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2706 // Don't forget the parens to enforce the proper binding.
2707 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2709 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2710 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
2711 FT->getResultType(), VK_RValue,
2713 ReplaceStmt(Exp, CE);
2717 Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2718 // synthesize declaration of helper functions needed in this routine.
2719 if (!SelGetUidFunctionDecl)
2720 SynthSelGetUidFunctionDecl();
2721 // use objc_msgSend() for all.
2722 if (!MsgSendFunctionDecl)
2723 SynthMsgSendFunctionDecl();
2724 if (!GetClassFunctionDecl)
2725 SynthGetClassFunctionDecl();
2727 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2728 SourceLocation StartLoc = Exp->getLocStart();
2729 SourceLocation EndLoc = Exp->getLocEnd();
2731 // Build the expression: __NSContainer_literal(int, ...).arr
2732 QualType IntQT = Context->IntTy;
2733 QualType NSArrayFType =
2734 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2735 std::string NSArrayFName("__NSContainer_literal");
2736 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2737 DeclRefExpr *NSArrayDRE =
2738 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2741 SmallVector<Expr*, 16> InitExprs;
2742 unsigned NumElements = Exp->getNumElements();
2743 unsigned UnsignedIntSize =
2744 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2745 Expr *count = IntegerLiteral::Create(*Context,
2746 llvm::APInt(UnsignedIntSize, NumElements),
2747 Context->UnsignedIntTy, SourceLocation());
2748 InitExprs.push_back(count);
2749 for (unsigned i = 0; i < NumElements; i++)
2750 InitExprs.push_back(Exp->getElement(i));
2751 Expr *NSArrayCallExpr =
2752 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
2753 NSArrayFType, VK_LValue, SourceLocation());
2755 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2757 &Context->Idents.get("arr"),
2758 Context->getPointerType(Context->VoidPtrTy), 0,
2759 /*BitWidth=*/0, /*Mutable=*/true,
2761 MemberExpr *ArrayLiteralME =
2762 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2764 ARRFD->getType(), VK_LValue,
2766 QualType ConstIdT = Context->getObjCIdType().withConst();
2767 CStyleCastExpr * ArrayLiteralObjects =
2768 NoTypeInfoCStyleCastExpr(Context,
2769 Context->getPointerType(ConstIdT),
2773 // Synthesize a call to objc_msgSend().
2774 SmallVector<Expr*, 32> MsgExprs;
2775 SmallVector<Expr*, 4> ClsExprs;
2776 QualType argType = Context->getPointerType(Context->CharTy);
2777 QualType expType = Exp->getType();
2779 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2780 ObjCInterfaceDecl *Class =
2781 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2783 IdentifierInfo *clsName = Class->getIdentifier();
2784 ClsExprs.push_back(StringLiteral::Create(*Context,
2786 StringLiteral::Ascii, false,
2787 argType, SourceLocation()));
2788 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2792 MsgExprs.push_back(Cls);
2794 // Create a call to sel_registerName("arrayWithObjects:count:").
2795 // it will be the 2nd argument.
2796 SmallVector<Expr*, 4> SelExprs;
2797 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2798 SelExprs.push_back(StringLiteral::Create(*Context,
2799 ArrayMethod->getSelector().getAsString(),
2800 StringLiteral::Ascii, false,
2801 argType, SourceLocation()));
2802 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2803 &SelExprs[0], SelExprs.size(),
2805 MsgExprs.push_back(SelExp);
2807 // (const id [])objects
2808 MsgExprs.push_back(ArrayLiteralObjects);
2811 Expr *cnt = IntegerLiteral::Create(*Context,
2812 llvm::APInt(UnsignedIntSize, NumElements),
2813 Context->UnsignedIntTy, SourceLocation());
2814 MsgExprs.push_back(cnt);
2817 SmallVector<QualType, 4> ArgTypes;
2818 ArgTypes.push_back(Context->getObjCIdType());
2819 ArgTypes.push_back(Context->getObjCSelType());
2820 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2821 E = ArrayMethod->param_end(); PI != E; ++PI)
2822 ArgTypes.push_back((*PI)->getType());
2824 QualType returnType = Exp->getType();
2825 // Get the type, we will need to reference it in a couple spots.
2826 QualType msgSendType = MsgSendFlavor->getType();
2828 // Create a reference to the objc_msgSend() declaration.
2829 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2830 VK_LValue, SourceLocation());
2832 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2833 Context->getPointerType(Context->VoidTy),
2836 // Now do the "normal" pointer to function cast.
2838 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2839 ArrayMethod->isVariadic());
2840 castType = Context->getPointerType(castType);
2841 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2844 // Don't forget the parens to enforce the proper binding.
2845 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2847 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2848 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
2849 FT->getResultType(), VK_RValue,
2851 ReplaceStmt(Exp, CE);
2855 Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2856 // synthesize declaration of helper functions needed in this routine.
2857 if (!SelGetUidFunctionDecl)
2858 SynthSelGetUidFunctionDecl();
2859 // use objc_msgSend() for all.
2860 if (!MsgSendFunctionDecl)
2861 SynthMsgSendFunctionDecl();
2862 if (!GetClassFunctionDecl)
2863 SynthGetClassFunctionDecl();
2865 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2866 SourceLocation StartLoc = Exp->getLocStart();
2867 SourceLocation EndLoc = Exp->getLocEnd();
2869 // Build the expression: __NSContainer_literal(int, ...).arr
2870 QualType IntQT = Context->IntTy;
2871 QualType NSDictFType =
2872 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2873 std::string NSDictFName("__NSContainer_literal");
2874 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2875 DeclRefExpr *NSDictDRE =
2876 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2879 SmallVector<Expr*, 16> KeyExprs;
2880 SmallVector<Expr*, 16> ValueExprs;
2882 unsigned NumElements = Exp->getNumElements();
2883 unsigned UnsignedIntSize =
2884 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2885 Expr *count = IntegerLiteral::Create(*Context,
2886 llvm::APInt(UnsignedIntSize, NumElements),
2887 Context->UnsignedIntTy, SourceLocation());
2888 KeyExprs.push_back(count);
2889 ValueExprs.push_back(count);
2890 for (unsigned i = 0; i < NumElements; i++) {
2891 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2892 KeyExprs.push_back(Element.Key);
2893 ValueExprs.push_back(Element.Value);
2896 // (const id [])objects
2897 Expr *NSValueCallExpr =
2898 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
2899 NSDictFType, VK_LValue, SourceLocation());
2901 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2903 &Context->Idents.get("arr"),
2904 Context->getPointerType(Context->VoidPtrTy), 0,
2905 /*BitWidth=*/0, /*Mutable=*/true,
2907 MemberExpr *DictLiteralValueME =
2908 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2910 ARRFD->getType(), VK_LValue,
2912 QualType ConstIdT = Context->getObjCIdType().withConst();
2913 CStyleCastExpr * DictValueObjects =
2914 NoTypeInfoCStyleCastExpr(Context,
2915 Context->getPointerType(ConstIdT),
2917 DictLiteralValueME);
2918 // (const id <NSCopying> [])keys
2919 Expr *NSKeyCallExpr =
2920 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2921 NSDictFType, VK_LValue, SourceLocation());
2923 MemberExpr *DictLiteralKeyME =
2924 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2926 ARRFD->getType(), VK_LValue,
2929 CStyleCastExpr * DictKeyObjects =
2930 NoTypeInfoCStyleCastExpr(Context,
2931 Context->getPointerType(ConstIdT),
2937 // Synthesize a call to objc_msgSend().
2938 SmallVector<Expr*, 32> MsgExprs;
2939 SmallVector<Expr*, 4> ClsExprs;
2940 QualType argType = Context->getPointerType(Context->CharTy);
2941 QualType expType = Exp->getType();
2943 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2944 ObjCInterfaceDecl *Class =
2945 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2947 IdentifierInfo *clsName = Class->getIdentifier();
2948 ClsExprs.push_back(StringLiteral::Create(*Context,
2950 StringLiteral::Ascii, false,
2951 argType, SourceLocation()));
2952 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2956 MsgExprs.push_back(Cls);
2958 // Create a call to sel_registerName("arrayWithObjects:count:").
2959 // it will be the 2nd argument.
2960 SmallVector<Expr*, 4> SelExprs;
2961 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2962 SelExprs.push_back(StringLiteral::Create(*Context,
2963 DictMethod->getSelector().getAsString(),
2964 StringLiteral::Ascii, false,
2965 argType, SourceLocation()));
2966 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2967 &SelExprs[0], SelExprs.size(),
2969 MsgExprs.push_back(SelExp);
2971 // (const id [])objects
2972 MsgExprs.push_back(DictValueObjects);
2974 // (const id <NSCopying> [])keys
2975 MsgExprs.push_back(DictKeyObjects);
2978 Expr *cnt = IntegerLiteral::Create(*Context,
2979 llvm::APInt(UnsignedIntSize, NumElements),
2980 Context->UnsignedIntTy, SourceLocation());
2981 MsgExprs.push_back(cnt);
2984 SmallVector<QualType, 8> ArgTypes;
2985 ArgTypes.push_back(Context->getObjCIdType());
2986 ArgTypes.push_back(Context->getObjCSelType());
2987 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2988 E = DictMethod->param_end(); PI != E; ++PI) {
2989 QualType T = (*PI)->getType();
2990 if (const PointerType* PT = T->getAs<PointerType>()) {
2991 QualType PointeeTy = PT->getPointeeType();
2992 convertToUnqualifiedObjCType(PointeeTy);
2993 T = Context->getPointerType(PointeeTy);
2995 ArgTypes.push_back(T);
2998 QualType returnType = Exp->getType();
2999 // Get the type, we will need to reference it in a couple spots.
3000 QualType msgSendType = MsgSendFlavor->getType();
3002 // Create a reference to the objc_msgSend() declaration.
3003 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3004 VK_LValue, SourceLocation());
3006 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3007 Context->getPointerType(Context->VoidTy),
3010 // Now do the "normal" pointer to function cast.
3012 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3013 DictMethod->isVariadic());
3014 castType = Context->getPointerType(castType);
3015 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3018 // Don't forget the parens to enforce the proper binding.
3019 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3021 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3022 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3023 FT->getResultType(), VK_RValue,
3025 ReplaceStmt(Exp, CE);
3029 // struct __rw_objc_super {
3030 // struct objc_object *object; struct objc_object *superClass;
3032 QualType RewriteModernObjC::getSuperStructType() {
3033 if (!SuperStructDecl) {
3034 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3035 SourceLocation(), SourceLocation(),
3036 &Context->Idents.get("__rw_objc_super"));
3037 QualType FieldTypes[2];
3039 // struct objc_object *object;
3040 FieldTypes[0] = Context->getObjCIdType();
3041 // struct objc_object *superClass;
3042 FieldTypes[1] = Context->getObjCIdType();
3045 for (unsigned i = 0; i < 2; ++i) {
3046 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3048 SourceLocation(), 0,
3055 SuperStructDecl->completeDefinition();
3057 return Context->getTagDeclType(SuperStructDecl);
3060 QualType RewriteModernObjC::getConstantStringStructType() {
3061 if (!ConstantStringDecl) {
3062 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3063 SourceLocation(), SourceLocation(),
3064 &Context->Idents.get("__NSConstantStringImpl"));
3065 QualType FieldTypes[4];
3067 // struct objc_object *receiver;
3068 FieldTypes[0] = Context->getObjCIdType();
3070 FieldTypes[1] = Context->IntTy;
3072 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3074 FieldTypes[3] = Context->LongTy;
3077 for (unsigned i = 0; i < 4; ++i) {
3078 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3081 SourceLocation(), 0,
3088 ConstantStringDecl->completeDefinition();
3090 return Context->getTagDeclType(ConstantStringDecl);
3093 /// getFunctionSourceLocation - returns start location of a function
3094 /// definition. Complication arises when function has declared as
3095 /// extern "C" or extern "C" {...}
3096 static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3098 if (FD->isExternC() && !FD->isMain()) {
3099 const DeclContext *DC = FD->getDeclContext();
3100 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3101 // if it is extern "C" {...}, return function decl's own location.
3102 if (!LSD->getRBraceLoc().isValid())
3103 return LSD->getExternLoc();
3105 if (FD->getStorageClassAsWritten() != SC_None)
3106 R.RewriteBlockLiteralFunctionDecl(FD);
3107 return FD->getTypeSpecStartLoc();
3110 void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3112 SourceLocation Location = D->getLocation();
3114 if (Location.isFileID()) {
3115 std::string LineString("\n#line ");
3116 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3117 LineString += utostr(PLoc.getLine());
3118 LineString += " \"";
3119 LineString += Lexer::Stringify(PLoc.getFilename());
3120 if (isa<ObjCMethodDecl>(D))
3122 else LineString += "\"\n";
3124 Location = D->getLocStart();
3125 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3126 if (FD->isExternC() && !FD->isMain()) {
3127 const DeclContext *DC = FD->getDeclContext();
3128 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3129 // if it is extern "C" {...}, return function decl's own location.
3130 if (!LSD->getRBraceLoc().isValid())
3131 Location = LSD->getExternLoc();
3134 InsertText(Location, LineString);
3138 /// SynthMsgSendStretCallExpr - This routine translates message expression
3139 /// into a call to objc_msgSend_stret() entry point. Tricky part is that
3140 /// nil check on receiver must be performed before calling objc_msgSend_stret.
3141 /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3142 /// msgSendType - function type of objc_msgSend_stret(...)
3143 /// returnType - Result type of the method being synthesized.
3144 /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3145 /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3146 /// starting with receiver.
3147 /// Method - Method being rewritten.
3148 Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3149 QualType msgSendType,
3150 QualType returnType,
3151 SmallVectorImpl<QualType> &ArgTypes,
3152 SmallVectorImpl<Expr*> &MsgExprs,
3153 ObjCMethodDecl *Method) {
3154 // Now do the "normal" pointer to function cast.
3155 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3156 Method ? Method->isVariadic() : false);
3157 castType = Context->getPointerType(castType);
3159 // build type for containing the objc_msgSend_stret object.
3160 static unsigned stretCount=0;
3161 std::string name = "__Stret"; name += utostr(stretCount);
3163 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3164 str += "struct "; str += name;
3167 str += "(id receiver, SEL sel";
3168 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3169 std::string ArgName = "arg"; ArgName += utostr(i);
3170 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3171 str += ", "; str += ArgName;
3174 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3175 std::string ArgName = "arg"; ArgName += utostr(i);
3176 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3177 Context->getPrintingPolicy());
3178 str += ", "; str += ArgName;
3182 str += "\t if (receiver == 0)\n";
3183 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3185 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3186 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3187 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3188 str += ", arg"; str += utostr(i);
3191 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3192 str += ", arg"; str += utostr(i);
3197 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3200 SourceLocation FunLocStart;
3202 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3204 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3205 FunLocStart = CurMethodDef->getLocStart();
3208 InsertText(FunLocStart, str);
3211 // AST for __Stretn(receiver, args).s;
3212 IdentifierInfo *ID = &Context->Idents.get(name);
3213 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3214 SourceLocation(), ID, castType, 0, SC_Extern,
3215 SC_None, false, false);
3216 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3218 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
3219 castType, VK_LValue, SourceLocation());
3221 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3223 &Context->Idents.get("s"),
3225 /*BitWidth=*/0, /*Mutable=*/true,
3227 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3228 FieldD->getType(), VK_LValue,
3234 Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3235 SourceLocation StartLoc,
3236 SourceLocation EndLoc) {
3237 if (!SelGetUidFunctionDecl)
3238 SynthSelGetUidFunctionDecl();
3239 if (!MsgSendFunctionDecl)
3240 SynthMsgSendFunctionDecl();
3241 if (!MsgSendSuperFunctionDecl)
3242 SynthMsgSendSuperFunctionDecl();
3243 if (!MsgSendStretFunctionDecl)
3244 SynthMsgSendStretFunctionDecl();
3245 if (!MsgSendSuperStretFunctionDecl)
3246 SynthMsgSendSuperStretFunctionDecl();
3247 if (!MsgSendFpretFunctionDecl)
3248 SynthMsgSendFpretFunctionDecl();
3249 if (!GetClassFunctionDecl)
3250 SynthGetClassFunctionDecl();
3251 if (!GetSuperClassFunctionDecl)
3252 SynthGetSuperClassFunctionDecl();
3253 if (!GetMetaClassFunctionDecl)
3254 SynthGetMetaClassFunctionDecl();
3256 // default to objc_msgSend().
3257 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3258 // May need to use objc_msgSend_stret() as well.
3259 FunctionDecl *MsgSendStretFlavor = 0;
3260 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3261 QualType resultType = mDecl->getResultType();
3262 if (resultType->isRecordType())
3263 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3264 else if (resultType->isRealFloatingType())
3265 MsgSendFlavor = MsgSendFpretFunctionDecl;
3268 // Synthesize a call to objc_msgSend().
3269 SmallVector<Expr*, 8> MsgExprs;
3270 switch (Exp->getReceiverKind()) {
3271 case ObjCMessageExpr::SuperClass: {
3272 MsgSendFlavor = MsgSendSuperFunctionDecl;
3273 if (MsgSendStretFlavor)
3274 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3275 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3277 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3279 SmallVector<Expr*, 4> InitExprs;
3281 // set the receiver to self, the first argument to all methods.
3282 InitExprs.push_back(
3283 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3285 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3287 Context->getObjCIdType(),
3290 ); // set the 'receiver'.
3292 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3293 SmallVector<Expr*, 8> ClsExprs;
3294 QualType argType = Context->getPointerType(Context->CharTy);
3295 ClsExprs.push_back(StringLiteral::Create(*Context,
3296 ClassDecl->getIdentifier()->getName(),
3297 StringLiteral::Ascii, false,
3298 argType, SourceLocation()));
3299 // (Class)objc_getClass("CurrentClass")
3300 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3306 ClsExprs.push_back(Cls);
3307 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3308 &ClsExprs[0], ClsExprs.size(),
3311 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3312 // To turn off a warning, type-cast to 'id'
3313 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3314 NoTypeInfoCStyleCastExpr(Context,
3315 Context->getObjCIdType(),
3317 // struct __rw_objc_super
3318 QualType superType = getSuperStructType();
3321 if (LangOpts.MicrosoftExt) {
3322 SynthSuperContructorFunctionDecl();
3323 // Simulate a contructor call...
3324 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
3325 false, superType, VK_LValue,
3327 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3328 superType, VK_LValue,
3330 // The code for super is a little tricky to prevent collision with
3331 // the structure definition in the header. The rewriter has it's own
3332 // internal definition (__rw_objc_super) that is uses. This is why
3333 // we need the cast below. For example:
3334 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3336 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3337 Context->getPointerType(SuperRep->getType()),
3338 VK_RValue, OK_Ordinary,
3340 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3341 Context->getPointerType(superType),
3342 CK_BitCast, SuperRep);
3344 // (struct __rw_objc_super) { <exprs from above> }
3346 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3348 TypeSourceInfo *superTInfo
3349 = Context->getTrivialTypeSourceInfo(superType);
3350 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3351 superType, VK_LValue,
3353 // struct __rw_objc_super *
3354 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3355 Context->getPointerType(SuperRep->getType()),
3356 VK_RValue, OK_Ordinary,
3359 MsgExprs.push_back(SuperRep);
3363 case ObjCMessageExpr::Class: {
3364 SmallVector<Expr*, 8> ClsExprs;
3365 QualType argType = Context->getPointerType(Context->CharTy);
3366 ObjCInterfaceDecl *Class
3367 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3368 IdentifierInfo *clsName = Class->getIdentifier();
3369 ClsExprs.push_back(StringLiteral::Create(*Context,
3371 StringLiteral::Ascii, false,
3372 argType, SourceLocation()));
3373 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3377 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3378 Context->getObjCIdType(),
3380 MsgExprs.push_back(ArgExpr);
3384 case ObjCMessageExpr::SuperInstance:{
3385 MsgSendFlavor = MsgSendSuperFunctionDecl;
3386 if (MsgSendStretFlavor)
3387 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3388 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3389 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3390 SmallVector<Expr*, 4> InitExprs;
3392 InitExprs.push_back(
3393 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3395 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3397 Context->getObjCIdType(),
3398 VK_RValue, SourceLocation()))
3399 ); // set the 'receiver'.
3401 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3402 SmallVector<Expr*, 8> ClsExprs;
3403 QualType argType = Context->getPointerType(Context->CharTy);
3404 ClsExprs.push_back(StringLiteral::Create(*Context,
3405 ClassDecl->getIdentifier()->getName(),
3406 StringLiteral::Ascii, false, argType,
3408 // (Class)objc_getClass("CurrentClass")
3409 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3414 ClsExprs.push_back(Cls);
3415 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3416 &ClsExprs[0], ClsExprs.size(),
3419 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3420 // To turn off a warning, type-cast to 'id'
3421 InitExprs.push_back(
3422 // set 'super class', using class_getSuperclass().
3423 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3425 // struct __rw_objc_super
3426 QualType superType = getSuperStructType();
3429 if (LangOpts.MicrosoftExt) {
3430 SynthSuperContructorFunctionDecl();
3431 // Simulate a contructor call...
3432 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
3433 false, superType, VK_LValue,
3435 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3436 superType, VK_LValue, SourceLocation());
3437 // The code for super is a little tricky to prevent collision with
3438 // the structure definition in the header. The rewriter has it's own
3439 // internal definition (__rw_objc_super) that is uses. This is why
3440 // we need the cast below. For example:
3441 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3443 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3444 Context->getPointerType(SuperRep->getType()),
3445 VK_RValue, OK_Ordinary,
3447 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3448 Context->getPointerType(superType),
3449 CK_BitCast, SuperRep);
3451 // (struct __rw_objc_super) { <exprs from above> }
3453 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3455 TypeSourceInfo *superTInfo
3456 = Context->getTrivialTypeSourceInfo(superType);
3457 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3458 superType, VK_RValue, ILE,
3461 MsgExprs.push_back(SuperRep);
3465 case ObjCMessageExpr::Instance: {
3466 // Remove all type-casts because it may contain objc-style types; e.g.
3468 Expr *recExpr = Exp->getInstanceReceiver();
3469 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3470 recExpr = CE->getSubExpr();
3471 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3472 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3473 ? CK_BlockPointerToObjCPointerCast
3474 : CK_CPointerToObjCPointerCast;
3476 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3478 MsgExprs.push_back(recExpr);
3483 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3484 SmallVector<Expr*, 8> SelExprs;
3485 QualType argType = Context->getPointerType(Context->CharTy);
3486 SelExprs.push_back(StringLiteral::Create(*Context,
3487 Exp->getSelector().getAsString(),
3488 StringLiteral::Ascii, false,
3489 argType, SourceLocation()));
3490 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3491 &SelExprs[0], SelExprs.size(),
3494 MsgExprs.push_back(SelExp);
3496 // Now push any user supplied arguments.
3497 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3498 Expr *userExpr = Exp->getArg(i);
3499 // Make all implicit casts explicit...ICE comes in handy:-)
3500 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3501 // Reuse the ICE type, it is exactly what the doctor ordered.
3502 QualType type = ICE->getType();
3503 if (needToScanForQualifiers(type))
3504 type = Context->getObjCIdType();
3505 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3506 (void)convertBlockPointerToFunctionPointer(type);
3507 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3509 if (SubExpr->getType()->isIntegralType(*Context) &&
3510 type->isBooleanType()) {
3511 CK = CK_IntegralToBoolean;
3512 } else if (type->isObjCObjectPointerType()) {
3513 if (SubExpr->getType()->isBlockPointerType()) {
3514 CK = CK_BlockPointerToObjCPointerCast;
3515 } else if (SubExpr->getType()->isPointerType()) {
3516 CK = CK_CPointerToObjCPointerCast;
3524 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3526 // Make id<P...> cast into an 'id' cast.
3527 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3528 if (CE->getType()->isObjCQualifiedIdType()) {
3529 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3530 userExpr = CE->getSubExpr();
3532 if (userExpr->getType()->isIntegralType(*Context)) {
3533 CK = CK_IntegralToPointer;
3534 } else if (userExpr->getType()->isBlockPointerType()) {
3535 CK = CK_BlockPointerToObjCPointerCast;
3536 } else if (userExpr->getType()->isPointerType()) {
3537 CK = CK_CPointerToObjCPointerCast;
3541 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3545 MsgExprs.push_back(userExpr);
3546 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3547 // out the argument in the original expression (since we aren't deleting
3548 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3549 //Exp->setArg(i, 0);
3551 // Generate the funky cast.
3553 SmallVector<QualType, 8> ArgTypes;
3554 QualType returnType;
3556 // Push 'id' and 'SEL', the 2 implicit arguments.
3557 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3558 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3560 ArgTypes.push_back(Context->getObjCIdType());
3561 ArgTypes.push_back(Context->getObjCSelType());
3562 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3563 // Push any user argument types.
3564 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3565 E = OMD->param_end(); PI != E; ++PI) {
3566 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3567 ? Context->getObjCIdType()
3569 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3570 (void)convertBlockPointerToFunctionPointer(t);
3571 ArgTypes.push_back(t);
3573 returnType = Exp->getType();
3574 convertToUnqualifiedObjCType(returnType);
3575 (void)convertBlockPointerToFunctionPointer(returnType);
3577 returnType = Context->getObjCIdType();
3579 // Get the type, we will need to reference it in a couple spots.
3580 QualType msgSendType = MsgSendFlavor->getType();
3582 // Create a reference to the objc_msgSend() declaration.
3583 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3584 VK_LValue, SourceLocation());
3586 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3587 // If we don't do this cast, we get the following bizarre warning/note:
3588 // xx.m:13: warning: function called through a non-compatible type
3589 // xx.m:13: note: if this code is reached, the program will abort
3590 cast = NoTypeInfoCStyleCastExpr(Context,
3591 Context->getPointerType(Context->VoidTy),
3594 // Now do the "normal" pointer to function cast.
3596 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3597 // If we don't have a method decl, force a variadic cast.
3598 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3599 castType = Context->getPointerType(castType);
3600 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3603 // Don't forget the parens to enforce the proper binding.
3604 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3606 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3607 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3608 FT->getResultType(), VK_RValue, EndLoc);
3609 Stmt *ReplacingStmt = CE;
3610 if (MsgSendStretFlavor) {
3611 // We have the method which returns a struct/union. Must also generate
3612 // call to objc_msgSend_stret and hang both varieties on a conditional
3613 // expression which dictate which one to envoke depending on size of
3614 // method's return type.
3616 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3617 msgSendType, returnType,
3619 Exp->getMethodDecl());
3621 // Build sizeof(returnType)
3622 UnaryExprOrTypeTraitExpr *sizeofExpr =
3623 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3624 Context->getTrivialTypeSourceInfo(returnType),
3625 Context->getSizeType(), SourceLocation(),
3627 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3628 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3629 // For X86 it is more complicated and some kind of target specific routine
3630 // is needed to decide what to do.
3632 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3633 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3634 llvm::APInt(IntSize, 8),
3637 BinaryOperator *lessThanExpr =
3638 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3639 VK_RValue, OK_Ordinary, SourceLocation(),
3641 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3642 ConditionalOperator *CondExpr =
3643 new (Context) ConditionalOperator(lessThanExpr,
3644 SourceLocation(), CE,
3645 SourceLocation(), STCE,
3646 returnType, VK_RValue, OK_Ordinary);
3647 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3650 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3651 return ReplacingStmt;
3654 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3655 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3658 // Now do the actual rewrite.
3659 ReplaceStmt(Exp, ReplacingStmt);
3661 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3662 return ReplacingStmt;
3665 // typedef struct objc_object Protocol;
3666 QualType RewriteModernObjC::getProtocolType() {
3667 if (!ProtocolTypeDecl) {
3668 TypeSourceInfo *TInfo
3669 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3670 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3671 SourceLocation(), SourceLocation(),
3672 &Context->Idents.get("Protocol"),
3675 return Context->getTypeDeclType(ProtocolTypeDecl);
3678 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3679 /// a synthesized/forward data reference (to the protocol's metadata).
3680 /// The forward references (and metadata) are generated in
3681 /// RewriteModernObjC::HandleTranslationUnit().
3682 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3683 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3684 Exp->getProtocol()->getNameAsString();
3685 IdentifierInfo *ID = &Context->Idents.get(Name);
3686 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3687 SourceLocation(), ID, getProtocolType(), 0,
3688 SC_Extern, SC_None);
3689 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3690 VK_LValue, SourceLocation());
3691 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3692 Context->getPointerType(DRE->getType()),
3693 VK_RValue, OK_Ordinary, SourceLocation());
3694 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3697 ReplaceStmt(Exp, castExpr);
3698 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3699 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3704 bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3705 const char *endBuf) {
3706 while (startBuf < endBuf) {
3707 if (*startBuf == '#') {
3709 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3711 if (!strncmp(startBuf, "if", strlen("if")) ||
3712 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3713 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3714 !strncmp(startBuf, "define", strlen("define")) ||
3715 !strncmp(startBuf, "undef", strlen("undef")) ||
3716 !strncmp(startBuf, "else", strlen("else")) ||
3717 !strncmp(startBuf, "elif", strlen("elif")) ||
3718 !strncmp(startBuf, "endif", strlen("endif")) ||
3719 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3720 !strncmp(startBuf, "include", strlen("include")) ||
3721 !strncmp(startBuf, "import", strlen("import")) ||
3722 !strncmp(startBuf, "include_next", strlen("include_next")))
3730 /// IsTagDefinedInsideClass - This routine checks that a named tagged type
3731 /// is defined inside an objective-c class. If so, it returns true.
3732 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3734 bool &IsNamedDefinition) {
3737 SourceLocation TagLocation;
3738 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3739 RD = RD->getDefinition();
3740 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3742 IsNamedDefinition = true;
3743 TagLocation = RD->getLocation();
3744 return Context->getSourceManager().isBeforeInTranslationUnit(
3745 IDecl->getLocation(), TagLocation);
3747 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3748 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3750 IsNamedDefinition = true;
3751 TagLocation = ED->getLocation();
3752 return Context->getSourceManager().isBeforeInTranslationUnit(
3753 IDecl->getLocation(), TagLocation);
3759 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3760 /// It handles elaborated types, as well as enum types in the process.
3761 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3762 std::string &Result) {
3763 if (isa<TypedefType>(Type)) {
3768 if (Type->isArrayType()) {
3769 QualType ElemTy = Context->getBaseElementType(Type);
3770 return RewriteObjCFieldDeclType(ElemTy, Result);
3772 else if (Type->isRecordType()) {
3773 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3774 if (RD->isCompleteDefinition()) {
3776 Result += "\n\tstruct ";
3777 else if (RD->isUnion())
3778 Result += "\n\tunion ";
3780 assert(false && "class not allowed as an ivar type");
3782 Result += RD->getName();
3783 if (GlobalDefinedTags.count(RD)) {
3784 // struct/union is defined globally, use it.
3789 for (RecordDecl::field_iterator i = RD->field_begin(),
3790 e = RD->field_end(); i != e; ++i) {
3792 RewriteObjCFieldDecl(FD, Result);
3798 else if (Type->isEnumeralType()) {
3799 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3800 if (ED->isCompleteDefinition()) {
3801 Result += "\n\tenum ";
3802 Result += ED->getName();
3803 if (GlobalDefinedTags.count(ED)) {
3804 // Enum is globall defined, use it.
3810 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3811 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3812 Result += "\t"; Result += EC->getName(); Result += " = ";
3813 llvm::APSInt Val = EC->getInitVal();
3814 Result += Val.toString(10);
3823 convertObjCTypeToCStyleType(Type);
3828 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3829 /// It handles elaborated types, as well as enum types in the process.
3830 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3831 std::string &Result) {
3832 QualType Type = fieldDecl->getType();
3833 std::string Name = fieldDecl->getNameAsString();
3835 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3836 if (!EleboratedType)
3837 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3839 if (fieldDecl->isBitField()) {
3840 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3842 else if (EleboratedType && Type->isArrayType()) {
3843 CanQualType CType = Context->getCanonicalType(Type);
3844 while (isa<ArrayType>(CType)) {
3845 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3847 llvm::APInt Dim = CAT->getSize();
3848 Result += utostr(Dim.getZExtValue());
3851 CType = CType->getAs<ArrayType>()->getElementType();
3858 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3859 /// named aggregate types into the input buffer.
3860 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3861 std::string &Result) {
3862 QualType Type = fieldDecl->getType();
3863 if (isa<TypedefType>(Type))
3865 if (Type->isArrayType())
3866 Type = Context->getBaseElementType(Type);
3867 ObjCContainerDecl *IDecl =
3868 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3871 if (Type->isRecordType()) {
3872 TD = Type->getAs<RecordType>()->getDecl();
3874 else if (Type->isEnumeralType()) {
3875 TD = Type->getAs<EnumType>()->getDecl();
3879 if (GlobalDefinedTags.count(TD))
3882 bool IsNamedDefinition = false;
3883 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3884 RewriteObjCFieldDeclType(Type, Result);
3887 if (IsNamedDefinition)
3888 GlobalDefinedTags.insert(TD);
3893 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3894 /// an objective-c class with ivars.
3895 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3896 std::string &Result) {
3897 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3898 assert(CDecl->getName() != "" &&
3899 "Name missing in SynthesizeObjCInternalStruct");
3900 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3901 SmallVector<ObjCIvarDecl *, 8> IVars;
3902 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3903 IVD; IVD = IVD->getNextIvar())
3904 IVars.push_back(IVD);
3906 SourceLocation LocStart = CDecl->getLocStart();
3907 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3909 const char *startBuf = SM->getCharacterData(LocStart);
3910 const char *endBuf = SM->getCharacterData(LocEnd);
3912 // If no ivars and no root or if its root, directly or indirectly,
3913 // have no ivars (thus not synthesized) then no need to synthesize this class.
3914 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3915 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3916 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3917 ReplaceText(LocStart, endBuf-startBuf, Result);
3921 // Insert named struct/union definitions inside class to
3922 // outer scope. This follows semantics of locally defined
3923 // struct/unions in objective-c classes.
3924 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3925 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3927 Result += "\nstruct ";
3928 Result += CDecl->getNameAsString();
3929 Result += "_IMPL {\n";
3931 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3932 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3933 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3934 Result += "_IVARS;\n";
3937 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3938 RewriteObjCFieldDecl(IVars[i], Result);
3941 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3942 ReplaceText(LocStart, endBuf-startBuf, Result);
3943 // Mark this struct as having been generated.
3944 if (!ObjCSynthesizedStructs.insert(CDecl))
3945 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3948 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3949 /// have been referenced in an ivar access expression.
3950 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3951 std::string &Result) {
3952 // write out ivar offset symbols which have been referenced in an ivar
3953 // access expression.
3954 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3957 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3958 e = Ivars.end(); i != e; i++) {
3959 ObjCIvarDecl *IvarDecl = (*i);
3961 if (LangOpts.MicrosoftExt)
3962 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3963 Result += "extern \"C\" ";
3964 if (LangOpts.MicrosoftExt &&
3965 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3966 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3967 Result += "__declspec(dllimport) ";
3969 Result += "unsigned long ";
3970 WriteInternalIvarName(CDecl, IvarDecl, Result);
3975 //===----------------------------------------------------------------------===//
3976 // Meta Data Emission
3977 //===----------------------------------------------------------------------===//
3980 /// RewriteImplementations - This routine rewrites all method implementations
3981 /// and emits meta-data.
3983 void RewriteModernObjC::RewriteImplementations() {
3984 int ClsDefCount = ClassImplementation.size();
3985 int CatDefCount = CategoryImplementation.size();
3987 // Rewrite implemented methods
3988 for (int i = 0; i < ClsDefCount; i++) {
3989 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3990 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3991 if (CDecl->isImplicitInterfaceDecl())
3993 "Legacy implicit interface rewriting not supported in moder abi");
3994 RewriteImplementationDecl(OIMP);
3997 for (int i = 0; i < CatDefCount; i++) {
3998 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3999 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4000 if (CDecl->isImplicitInterfaceDecl())
4002 "Legacy implicit interface rewriting not supported in moder abi");
4003 RewriteImplementationDecl(CIMP);
4007 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4008 const std::string &Name,
4009 ValueDecl *VD, bool def) {
4010 assert(BlockByRefDeclNo.count(VD) &&
4011 "RewriteByRefString: ByRef decl missing");
4013 ResultStr += "struct ";
4014 ResultStr += "__Block_byref_" + Name +
4015 "_" + utostr(BlockByRefDeclNo[VD]) ;
4018 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4019 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4020 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4024 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4027 const FunctionType *AFT = CE->getFunctionType();
4028 QualType RT = AFT->getResultType();
4029 std::string StructRef = "struct " + Tag;
4030 SourceLocation BlockLoc = CE->getExprLoc();
4032 ConvertSourceLocationToLineDirective(BlockLoc, S);
4034 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4035 funcName.str() + "_block_func_" + utostr(i);
4037 BlockDecl *BD = CE->getBlockDecl();
4039 if (isa<FunctionNoProtoType>(AFT)) {
4040 // No user-supplied arguments. Still need to pass in a pointer to the
4041 // block (to reference imported block decl refs).
4042 S += "(" + StructRef + " *__cself)";
4043 } else if (BD->param_empty()) {
4044 S += "(" + StructRef + " *__cself)";
4046 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4047 assert(FT && "SynthesizeBlockFunc: No function proto");
4049 // first add the implicit argument.
4050 S += StructRef + " *__cself, ";
4051 std::string ParamStr;
4052 for (BlockDecl::param_iterator AI = BD->param_begin(),
4053 E = BD->param_end(); AI != E; ++AI) {
4054 if (AI != BD->param_begin()) S += ", ";
4055 ParamStr = (*AI)->getNameAsString();
4056 QualType QT = (*AI)->getType();
4057 (void)convertBlockPointerToFunctionPointer(QT);
4058 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4061 if (FT->isVariadic()) {
4062 if (!BD->param_empty()) S += ", ";
4069 // Create local declarations to avoid rewriting all closure decl ref exprs.
4070 // First, emit a declaration for all "by ref" decls.
4071 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4072 E = BlockByRefDecls.end(); I != E; ++I) {
4074 std::string Name = (*I)->getNameAsString();
4075 std::string TypeString;
4076 RewriteByRefString(TypeString, Name, (*I));
4078 Name = TypeString + Name;
4079 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4081 // Next, emit a declaration for all "by copy" declarations.
4082 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4083 E = BlockByCopyDecls.end(); I != E; ++I) {
4085 // Handle nested closure invocation. For example:
4087 // void (^myImportedClosure)(void);
4088 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4090 // void (^anotherClosure)(void);
4091 // anotherClosure = ^(void) {
4092 // myImportedClosure(); // import and invoke the closure
4095 if (isTopLevelBlockPointerType((*I)->getType())) {
4096 RewriteBlockPointerTypeVariable(S, (*I));
4098 RewriteBlockPointerType(S, (*I)->getType());
4100 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4103 std::string Name = (*I)->getNameAsString();
4104 QualType QT = (*I)->getType();
4105 if (HasLocalVariableExternalStorage(*I))
4106 QT = Context->getPointerType(QT);
4107 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4108 S += Name + " = __cself->" +
4109 (*I)->getNameAsString() + "; // bound by copy\n";
4112 std::string RewrittenStr = RewrittenBlockExprs[CE];
4113 const char *cstr = RewrittenStr.c_str();
4114 while (*cstr++ != '{') ;
4120 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4123 std::string StructRef = "struct " + Tag;
4124 std::string S = "static void __";
4127 S += "_block_copy_" + utostr(i);
4128 S += "(" + StructRef;
4129 S += "*dst, " + StructRef;
4131 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4132 E = ImportedBlockDecls.end(); I != E; ++I) {
4133 ValueDecl *VD = (*I);
4134 S += "_Block_object_assign((void*)&dst->";
4135 S += (*I)->getNameAsString();
4136 S += ", (void*)src->";
4137 S += (*I)->getNameAsString();
4138 if (BlockByRefDeclsPtrSet.count((*I)))
4139 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4140 else if (VD->getType()->isBlockPointerType())
4141 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4143 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4147 S += "\nstatic void __";
4149 S += "_block_dispose_" + utostr(i);
4150 S += "(" + StructRef;
4152 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4153 E = ImportedBlockDecls.end(); I != E; ++I) {
4154 ValueDecl *VD = (*I);
4155 S += "_Block_object_dispose((void*)src->";
4156 S += (*I)->getNameAsString();
4157 if (BlockByRefDeclsPtrSet.count((*I)))
4158 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4159 else if (VD->getType()->isBlockPointerType())
4160 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4162 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4168 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4170 std::string S = "\nstruct " + Tag;
4171 std::string Constructor = " " + Tag;
4173 S += " {\n struct __block_impl impl;\n";
4174 S += " struct " + Desc;
4177 Constructor += "(void *fp, "; // Invoke function pointer.
4178 Constructor += "struct " + Desc; // Descriptor pointer.
4179 Constructor += " *desc";
4181 if (BlockDeclRefs.size()) {
4182 // Output all "by copy" declarations.
4183 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4184 E = BlockByCopyDecls.end(); I != E; ++I) {
4186 std::string FieldName = (*I)->getNameAsString();
4187 std::string ArgName = "_" + FieldName;
4188 // Handle nested closure invocation. For example:
4190 // void (^myImportedBlock)(void);
4191 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4193 // void (^anotherBlock)(void);
4194 // anotherBlock = ^(void) {
4195 // myImportedBlock(); // import and invoke the closure
4198 if (isTopLevelBlockPointerType((*I)->getType())) {
4199 S += "struct __block_impl *";
4200 Constructor += ", void *" + ArgName;
4202 QualType QT = (*I)->getType();
4203 if (HasLocalVariableExternalStorage(*I))
4204 QT = Context->getPointerType(QT);
4205 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4206 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4207 Constructor += ", " + ArgName;
4209 S += FieldName + ";\n";
4211 // Output all "by ref" declarations.
4212 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4213 E = BlockByRefDecls.end(); I != E; ++I) {
4215 std::string FieldName = (*I)->getNameAsString();
4216 std::string ArgName = "_" + FieldName;
4218 std::string TypeString;
4219 RewriteByRefString(TypeString, FieldName, (*I));
4221 FieldName = TypeString + FieldName;
4222 ArgName = TypeString + ArgName;
4223 Constructor += ", " + ArgName;
4225 S += FieldName + "; // by ref\n";
4227 // Finish writing the constructor.
4228 Constructor += ", int flags=0)";
4229 // Initialize all "by copy" arguments.
4230 bool firsTime = true;
4231 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4232 E = BlockByCopyDecls.end(); I != E; ++I) {
4233 std::string Name = (*I)->getNameAsString();
4235 Constructor += " : ";
4239 Constructor += ", ";
4240 if (isTopLevelBlockPointerType((*I)->getType()))
4241 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4243 Constructor += Name + "(_" + Name + ")";
4245 // Initialize all "by ref" arguments.
4246 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4247 E = BlockByRefDecls.end(); I != E; ++I) {
4248 std::string Name = (*I)->getNameAsString();
4250 Constructor += " : ";
4254 Constructor += ", ";
4255 Constructor += Name + "(_" + Name + "->__forwarding)";
4258 Constructor += " {\n";
4260 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4262 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4263 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4265 Constructor += " Desc = desc;\n";
4267 // Finish writing the constructor.
4268 Constructor += ", int flags=0) {\n";
4270 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4272 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4273 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4274 Constructor += " Desc = desc;\n";
4277 Constructor += "}\n";
4283 std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4284 std::string ImplTag, int i,
4287 std::string S = "\nstatic struct " + DescTag;
4289 S += " {\n size_t reserved;\n";
4290 S += " size_t Block_size;\n";
4292 S += " void (*copy)(struct ";
4293 S += ImplTag; S += "*, struct ";
4294 S += ImplTag; S += "*);\n";
4296 S += " void (*dispose)(struct ";
4297 S += ImplTag; S += "*);\n";
4301 S += DescTag + "_DATA = { 0, sizeof(struct ";
4304 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4305 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4311 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4312 StringRef FunName) {
4313 bool RewriteSC = (GlobalVarDecl &&
4315 GlobalVarDecl->getStorageClass() == SC_Static &&
4316 GlobalVarDecl->getType().getCVRQualifiers());
4318 std::string SC(" void __");
4319 SC += GlobalVarDecl->getNameAsString();
4321 InsertText(FunLocStart, SC);
4324 // Insert closures that were part of the function.
4325 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4326 CollectBlockDeclRefInfo(Blocks[i]);
4327 // Need to copy-in the inner copied-in variables not actually used in this
4329 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4330 DeclRefExpr *Exp = InnerDeclRefs[count++];
4331 ValueDecl *VD = Exp->getDecl();
4332 BlockDeclRefs.push_back(Exp);
4333 if (!VD->hasAttr<BlocksAttr>()) {
4334 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4335 BlockByCopyDeclsPtrSet.insert(VD);
4336 BlockByCopyDecls.push_back(VD);
4341 if (!BlockByRefDeclsPtrSet.count(VD)) {
4342 BlockByRefDeclsPtrSet.insert(VD);
4343 BlockByRefDecls.push_back(VD);
4346 // imported objects in the inner blocks not used in the outer
4347 // blocks must be copied/disposed in the outer block as well.
4348 if (VD->getType()->isObjCObjectPointerType() ||
4349 VD->getType()->isBlockPointerType())
4350 ImportedBlockDecls.insert(VD);
4353 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4354 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4356 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4358 InsertText(FunLocStart, CI);
4360 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4362 InsertText(FunLocStart, CF);
4364 if (ImportedBlockDecls.size()) {
4365 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4366 InsertText(FunLocStart, HF);
4368 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4369 ImportedBlockDecls.size() > 0);
4370 InsertText(FunLocStart, BD);
4372 BlockDeclRefs.clear();
4373 BlockByRefDecls.clear();
4374 BlockByRefDeclsPtrSet.clear();
4375 BlockByCopyDecls.clear();
4376 BlockByCopyDeclsPtrSet.clear();
4377 ImportedBlockDecls.clear();
4380 // Must insert any 'const/volatile/static here. Since it has been
4381 // removed as result of rewriting of block literals.
4383 if (GlobalVarDecl->getStorageClass() == SC_Static)
4385 if (GlobalVarDecl->getType().isConstQualified())
4387 if (GlobalVarDecl->getType().isVolatileQualified())
4389 if (GlobalVarDecl->getType().isRestrictQualified())
4391 InsertText(FunLocStart, SC);
4393 if (GlobalConstructionExp) {
4394 // extra fancy dance for global literal expression.
4396 // Always the latest block expression on the block stack.
4397 std::string Tag = "__";
4399 Tag += "_block_impl_";
4400 Tag += utostr(Blocks.size()-1);
4401 std::string globalBuf = "static ";
4402 globalBuf += Tag; globalBuf += " ";
4405 llvm::raw_string_ostream constructorExprBuf(SStr);
4406 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
4407 PrintingPolicy(LangOpts));
4408 globalBuf += constructorExprBuf.str();
4410 InsertText(FunLocStart, globalBuf);
4411 GlobalConstructionExp = 0;
4415 InnerDeclRefsCount.clear();
4416 InnerDeclRefs.clear();
4417 RewrittenBlockExprs.clear();
4420 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4421 SourceLocation FunLocStart =
4422 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4423 : FD->getTypeSpecStartLoc();
4424 StringRef FuncName = FD->getName();
4426 SynthesizeBlockLiterals(FunLocStart, FuncName);
4429 static void BuildUniqueMethodName(std::string &Name,
4430 ObjCMethodDecl *MD) {
4431 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4432 Name = IFace->getName();
4433 Name += "__" + MD->getSelector().getAsString();
4434 // Convert colons to underscores.
4435 std::string::size_type loc = 0;
4436 while ((loc = Name.find(":", loc)) != std::string::npos)
4437 Name.replace(loc, 1, "_");
4440 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4441 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4442 //SourceLocation FunLocStart = MD->getLocStart();
4443 SourceLocation FunLocStart = MD->getLocStart();
4444 std::string FuncName;
4445 BuildUniqueMethodName(FuncName, MD);
4446 SynthesizeBlockLiterals(FunLocStart, FuncName);
4449 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4450 for (Stmt::child_range CI = S->children(); CI; ++CI)
4452 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4453 GetBlockDeclRefExprs(CBE->getBody());
4455 GetBlockDeclRefExprs(*CI);
4457 // Handle specific things.
4458 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4459 if (DRE->refersToEnclosingLocal()) {
4460 // FIXME: Handle enums.
4461 if (!isa<FunctionDecl>(DRE->getDecl()))
4462 BlockDeclRefs.push_back(DRE);
4463 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4464 BlockDeclRefs.push_back(DRE);
4471 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4472 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
4473 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4474 for (Stmt::child_range CI = S->children(); CI; ++CI)
4476 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4477 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4478 GetInnerBlockDeclRefExprs(CBE->getBody(),
4483 GetInnerBlockDeclRefExprs(*CI,
4488 // Handle specific things.
4489 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4490 if (DRE->refersToEnclosingLocal()) {
4491 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4492 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4493 InnerBlockDeclRefs.push_back(DRE);
4494 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4495 if (Var->isFunctionOrMethodVarDecl())
4496 ImportedLocalExternalDecls.insert(Var);
4503 /// convertObjCTypeToCStyleType - This routine converts such objc types
4504 /// as qualified objects, and blocks to their closest c/c++ types that
4505 /// it can. It returns true if input type was modified.
4506 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4508 convertBlockPointerToFunctionPointer(T);
4509 if (T->isFunctionPointerType()) {
4511 if (const PointerType* PT = T->getAs<PointerType>()) {
4512 PointeeTy = PT->getPointeeType();
4513 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4514 T = convertFunctionTypeOfBlocks(FT);
4515 T = Context->getPointerType(T);
4520 convertToUnqualifiedObjCType(T);
4524 /// convertFunctionTypeOfBlocks - This routine converts a function type
4525 /// whose result type may be a block pointer or whose argument type(s)
4526 /// might be block pointers to an equivalent function type replacing
4527 /// all block pointers to function pointers.
4528 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4529 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4530 // FTP will be null for closures that don't take arguments.
4531 // Generate a funky cast.
4532 SmallVector<QualType, 8> ArgTypes;
4533 QualType Res = FT->getResultType();
4534 bool modified = convertObjCTypeToCStyleType(Res);
4537 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4538 E = FTP->arg_type_end(); I && (I != E); ++I) {
4540 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4541 if (convertObjCTypeToCStyleType(t))
4543 ArgTypes.push_back(t);
4548 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4549 else FuncType = QualType(FT, 0);
4553 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4554 // Navigate to relevant type information.
4555 const BlockPointerType *CPT = 0;
4557 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4558 CPT = DRE->getType()->getAs<BlockPointerType>();
4559 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4560 CPT = MExpr->getType()->getAs<BlockPointerType>();
4562 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4563 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4565 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4566 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4567 else if (const ConditionalOperator *CEXPR =
4568 dyn_cast<ConditionalOperator>(BlockExp)) {
4569 Expr *LHSExp = CEXPR->getLHS();
4570 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4571 Expr *RHSExp = CEXPR->getRHS();
4572 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4573 Expr *CONDExp = CEXPR->getCond();
4574 ConditionalOperator *CondExpr =
4575 new (Context) ConditionalOperator(CONDExp,
4576 SourceLocation(), cast<Expr>(LHSStmt),
4577 SourceLocation(), cast<Expr>(RHSStmt),
4578 Exp->getType(), VK_RValue, OK_Ordinary);
4580 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4581 CPT = IRE->getType()->getAs<BlockPointerType>();
4582 } else if (const PseudoObjectExpr *POE
4583 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4584 CPT = POE->getType()->castAs<BlockPointerType>();
4586 assert(1 && "RewriteBlockClass: Bad type");
4588 assert(CPT && "RewriteBlockClass: Bad type");
4589 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4590 assert(FT && "RewriteBlockClass: Bad type");
4591 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4592 // FTP will be null for closures that don't take arguments.
4594 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4595 SourceLocation(), SourceLocation(),
4596 &Context->Idents.get("__block_impl"));
4597 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4599 // Generate a funky cast.
4600 SmallVector<QualType, 8> ArgTypes;
4602 // Push the block argument type.
4603 ArgTypes.push_back(PtrBlock);
4605 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4606 E = FTP->arg_type_end(); I && (I != E); ++I) {
4608 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4609 if (!convertBlockPointerToFunctionPointer(t))
4610 convertToUnqualifiedObjCType(t);
4611 ArgTypes.push_back(t);
4614 // Now do the pointer to function cast.
4615 QualType PtrToFuncCastType
4616 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4618 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4620 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4622 const_cast<Expr*>(BlockExp));
4623 // Don't forget the parens to enforce the proper binding.
4624 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4628 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4630 &Context->Idents.get("FuncPtr"),
4631 Context->VoidPtrTy, 0,
4632 /*BitWidth=*/0, /*Mutable=*/true,
4634 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4635 FD->getType(), VK_LValue,
4639 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4641 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4643 SmallVector<Expr*, 8> BlkExprs;
4644 // Add the implicit argument.
4645 BlkExprs.push_back(BlkCast);
4646 // Add the user arguments.
4647 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4648 E = Exp->arg_end(); I != E; ++I) {
4649 BlkExprs.push_back(*I);
4651 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
4652 Exp->getType(), VK_RValue,
4657 // We need to return the rewritten expression to handle cases where the
4658 // DeclRefExpr is embedded in another expression being rewritten.
4665 // void (^myblock)() = ^() {
4666 // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4670 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4671 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4672 // for each DeclRefExp where BYREFVAR is name of the variable.
4673 ValueDecl *VD = DeclRefExp->getDecl();
4674 bool isArrow = DeclRefExp->refersToEnclosingLocal();
4676 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4678 &Context->Idents.get("__forwarding"),
4679 Context->VoidPtrTy, 0,
4680 /*BitWidth=*/0, /*Mutable=*/true,
4682 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4683 FD, SourceLocation(),
4684 FD->getType(), VK_LValue,
4687 StringRef Name = VD->getName();
4688 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4689 &Context->Idents.get(Name),
4690 Context->VoidPtrTy, 0,
4691 /*BitWidth=*/0, /*Mutable=*/true,
4693 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4694 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4698 // Need parens to enforce precedence.
4699 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4700 DeclRefExp->getExprLoc(),
4702 ReplaceStmt(DeclRefExp, PE);
4706 // Rewrites the imported local variable V with external storage
4707 // (static, extern, etc.) as *V
4709 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4710 ValueDecl *VD = DRE->getDecl();
4711 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4712 if (!ImportedLocalExternalDecls.count(Var))
4714 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4715 VK_LValue, OK_Ordinary,
4716 DRE->getLocation());
4717 // Need parens to enforce precedence.
4718 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4720 ReplaceStmt(DRE, PE);
4724 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4725 SourceLocation LocStart = CE->getLParenLoc();
4726 SourceLocation LocEnd = CE->getRParenLoc();
4728 // Need to avoid trying to rewrite synthesized casts.
4729 if (LocStart.isInvalid())
4731 // Need to avoid trying to rewrite casts contained in macros.
4732 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4735 const char *startBuf = SM->getCharacterData(LocStart);
4736 const char *endBuf = SM->getCharacterData(LocEnd);
4737 QualType QT = CE->getType();
4738 const Type* TypePtr = QT->getAs<Type>();
4739 if (isa<TypeOfExprType>(TypePtr)) {
4740 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4741 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4742 std::string TypeAsString = "(";
4743 RewriteBlockPointerType(TypeAsString, QT);
4744 TypeAsString += ")";
4745 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4748 // advance the location to startArgList.
4749 const char *argPtr = startBuf;
4751 while (*argPtr++ && (argPtr < endBuf)) {
4754 // Replace the '^' with '*'.
4755 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4756 ReplaceText(LocStart, 1, "*");
4763 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4764 CastKind CastKind = IC->getCastKind();
4765 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4766 CastKind != CK_AnyPointerToBlockPointerCast)
4769 QualType QT = IC->getType();
4770 (void)convertBlockPointerToFunctionPointer(QT);
4771 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4772 std::string Str = "(";
4775 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4780 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4781 SourceLocation DeclLoc = FD->getLocation();
4782 unsigned parenCount = 0;
4784 // We have 1 or more arguments that have closure pointers.
4785 const char *startBuf = SM->getCharacterData(DeclLoc);
4786 const char *startArgList = strchr(startBuf, '(');
4788 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4791 // advance the location to startArgList.
4792 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4793 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4795 const char *argPtr = startArgList;
4797 while (*argPtr++ && parenCount) {
4800 // Replace the '^' with '*'.
4801 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4802 ReplaceText(DeclLoc, 1, "*");
4815 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4816 const FunctionProtoType *FTP;
4817 const PointerType *PT = QT->getAs<PointerType>();
4819 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4821 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4822 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4823 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4826 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4827 E = FTP->arg_type_end(); I != E; ++I)
4828 if (isTopLevelBlockPointerType(*I))
4834 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4835 const FunctionProtoType *FTP;
4836 const PointerType *PT = QT->getAs<PointerType>();
4838 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4840 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4841 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4842 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4845 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4846 E = FTP->arg_type_end(); I != E; ++I) {
4847 if ((*I)->isObjCQualifiedIdType())
4849 if ((*I)->isObjCObjectPointerType() &&
4850 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4858 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4859 const char *&RParen) {
4860 const char *argPtr = strchr(Name, '(');
4861 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4863 LParen = argPtr; // output the start.
4864 argPtr++; // skip past the left paren.
4865 unsigned parenCount = 1;
4867 while (*argPtr && parenCount) {
4869 case '(': parenCount++; break;
4870 case ')': parenCount--; break;
4873 if (parenCount) argPtr++;
4875 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4876 RParen = argPtr; // output the end
4879 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4880 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4881 RewriteBlockPointerFunctionArgs(FD);
4884 // Handle Variables and Typedefs.
4885 SourceLocation DeclLoc = ND->getLocation();
4887 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4888 DeclT = VD->getType();
4889 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4890 DeclT = TDD->getUnderlyingType();
4891 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4892 DeclT = FD->getType();
4894 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4896 const char *startBuf = SM->getCharacterData(DeclLoc);
4897 const char *endBuf = startBuf;
4898 // scan backward (from the decl location) for the end of the previous decl.
4899 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4901 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4903 unsigned OrigLength=0;
4904 // *startBuf != '^' if we are dealing with a pointer to function that
4905 // may take block argument types (which will be handled below).
4906 if (*startBuf == '^') {
4907 // Replace the '^' with '*', computing a negative offset.
4912 while (*startBuf != ')') {
4920 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4921 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4922 // Replace the '^' with '*' for arguments.
4923 // Replace id<P> with id/*<>*/
4924 DeclLoc = ND->getLocation();
4925 startBuf = SM->getCharacterData(DeclLoc);
4926 const char *argListBegin, *argListEnd;
4927 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4928 while (argListBegin < argListEnd) {
4929 if (*argListBegin == '^')
4931 else if (*argListBegin == '<') {
4933 buf += *argListBegin++;
4935 while (*argListBegin != '>') {
4936 buf += *argListBegin++;
4939 buf += *argListBegin;
4943 buf += *argListBegin;
4950 ReplaceText(Start, OrigLength, buf);
4956 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4957 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4958 /// struct Block_byref_id_object *src) {
4959 /// _Block_object_assign (&_dest->object, _src->object,
4960 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4961 /// [|BLOCK_FIELD_IS_WEAK]) // object
4962 /// _Block_object_assign(&_dest->object, _src->object,
4963 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4964 /// [|BLOCK_FIELD_IS_WEAK]) // block
4967 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4968 /// _Block_object_dispose(_src->object,
4969 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4970 /// [|BLOCK_FIELD_IS_WEAK]) // object
4971 /// _Block_object_dispose(_src->object,
4972 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4973 /// [|BLOCK_FIELD_IS_WEAK]) // block
4976 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4979 if (CopyDestroyCache.count(flag))
4981 CopyDestroyCache.insert(flag);
4982 S = "static void __Block_byref_id_object_copy_";
4984 S += "(void *dst, void *src) {\n";
4986 // offset into the object pointer is computed as:
4987 // void * + void* + int + int + void* + void *
4989 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4990 unsigned VoidPtrSize =
4991 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4993 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4994 S += " _Block_object_assign((char*)dst + ";
4995 S += utostr(offset);
4996 S += ", *(void * *) ((char*)src + ";
4997 S += utostr(offset);
5002 S += "static void __Block_byref_id_object_dispose_";
5004 S += "(void *src) {\n";
5005 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5006 S += utostr(offset);
5013 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
5014 /// the declaration into:
5015 /// struct __Block_byref_ND {
5016 /// void *__isa; // NULL for everything except __weak pointers
5017 /// struct __Block_byref_ND *__forwarding;
5018 /// int32_t __flags;
5020 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5021 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5025 /// It then replaces declaration of ND variable with:
5026 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5027 /// __size=sizeof(struct __Block_byref_ND),
5028 /// ND=initializer-if-any};
5031 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5035 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5036 if (DeclLoc.isInvalid())
5037 // If type location is missing, it is because of missing type (a warning).
5038 // Use variable's location which is good for this case.
5039 DeclLoc = ND->getLocation();
5040 const char *startBuf = SM->getCharacterData(DeclLoc);
5041 SourceLocation X = ND->getLocEnd();
5042 X = SM->getExpansionLoc(X);
5043 const char *endBuf = SM->getCharacterData(X);
5044 std::string Name(ND->getNameAsString());
5045 std::string ByrefType;
5046 RewriteByRefString(ByrefType, Name, ND, true);
5047 ByrefType += " {\n";
5048 ByrefType += " void *__isa;\n";
5049 RewriteByRefString(ByrefType, Name, ND);
5050 ByrefType += " *__forwarding;\n";
5051 ByrefType += " int __flags;\n";
5052 ByrefType += " int __size;\n";
5053 // Add void *__Block_byref_id_object_copy;
5054 // void *__Block_byref_id_object_dispose; if needed.
5055 QualType Ty = ND->getType();
5056 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5057 if (HasCopyAndDispose) {
5058 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5059 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5063 (void)convertBlockPointerToFunctionPointer(T);
5064 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5066 ByrefType += " " + Name + ";\n";
5067 ByrefType += "};\n";
5068 // Insert this type in global scope. It is needed by helper function.
5069 SourceLocation FunLocStart;
5071 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5073 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5074 FunLocStart = CurMethodDef->getLocStart();
5076 InsertText(FunLocStart, ByrefType);
5078 if (Ty.isObjCGCWeak()) {
5079 flag |= BLOCK_FIELD_IS_WEAK;
5082 if (HasCopyAndDispose) {
5083 flag = BLOCK_BYREF_CALLER;
5084 QualType Ty = ND->getType();
5085 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5086 if (Ty->isBlockPointerType())
5087 flag |= BLOCK_FIELD_IS_BLOCK;
5089 flag |= BLOCK_FIELD_IS_OBJECT;
5090 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5092 InsertText(FunLocStart, HF);
5095 // struct __Block_byref_ND ND =
5096 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5097 // initializer-if-any};
5098 bool hasInit = (ND->getInit() != 0);
5099 // FIXME. rewriter does not support __block c++ objects which
5100 // require construction.
5102 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5103 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5104 if (CXXDecl && CXXDecl->isDefaultConstructor())
5109 if (HasCopyAndDispose)
5110 flags |= BLOCK_HAS_COPY_DISPOSE;
5111 Name = ND->getNameAsString();
5113 RewriteByRefString(ByrefType, Name, ND);
5114 std::string ForwardingCastType("(");
5115 ForwardingCastType += ByrefType + " *)";
5116 ByrefType += " " + Name + " = {(void*)";
5117 ByrefType += utostr(isa);
5118 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5119 ByrefType += utostr(flags);
5121 ByrefType += "sizeof(";
5122 RewriteByRefString(ByrefType, Name, ND);
5124 if (HasCopyAndDispose) {
5125 ByrefType += ", __Block_byref_id_object_copy_";
5126 ByrefType += utostr(flag);
5127 ByrefType += ", __Block_byref_id_object_dispose_";
5128 ByrefType += utostr(flag);
5132 // In multiple __block declarations, and for all but 1st declaration,
5133 // find location of the separating comma. This would be start location
5134 // where new text is to be inserted.
5135 DeclLoc = ND->getLocation();
5136 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5137 const char *commaBuf = startDeclBuf;
5138 while (*commaBuf != ',')
5140 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5141 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5142 startBuf = commaBuf;
5146 ByrefType += "};\n";
5147 unsigned nameSize = Name.size();
5148 // for block or function pointer declaration. Name is aleady
5149 // part of the declaration.
5150 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5152 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5156 SourceLocation startLoc;
5157 Expr *E = ND->getInit();
5158 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5159 startLoc = ECE->getLParenLoc();
5161 startLoc = E->getLocStart();
5162 startLoc = SM->getExpansionLoc(startLoc);
5163 endBuf = SM->getCharacterData(startLoc);
5164 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5166 const char separator = lastDecl ? ';' : ',';
5167 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5168 const char *separatorBuf = strchr(startInitializerBuf, separator);
5169 assert((*separatorBuf == separator) &&
5170 "RewriteByRefVar: can't find ';' or ','");
5171 SourceLocation separatorLoc =
5172 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5174 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5179 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5180 // Add initializers for any closure decl refs.
5181 GetBlockDeclRefExprs(Exp->getBody());
5182 if (BlockDeclRefs.size()) {
5183 // Unique all "by copy" declarations.
5184 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5185 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5186 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5187 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5188 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5191 // Unique all "by ref" declarations.
5192 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5193 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5194 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5195 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5196 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5199 // Find any imported blocks...they will need special attention.
5200 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5201 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5202 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5203 BlockDeclRefs[i]->getType()->isBlockPointerType())
5204 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5208 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5209 IdentifierInfo *ID = &Context->Idents.get(name);
5210 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5211 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5212 SourceLocation(), ID, FType, 0, SC_Extern,
5213 SC_None, false, false);
5216 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5217 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
5219 const BlockDecl *block = Exp->getBlockDecl();
5221 Blocks.push_back(Exp);
5223 CollectBlockDeclRefInfo(Exp);
5225 // Add inner imported variables now used in current block.
5226 int countOfInnerDecls = 0;
5227 if (!InnerBlockDeclRefs.empty()) {
5228 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5229 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5230 ValueDecl *VD = Exp->getDecl();
5231 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5232 // We need to save the copied-in variables in nested
5233 // blocks because it is needed at the end for some of the API generations.
5234 // See SynthesizeBlockLiterals routine.
5235 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5236 BlockDeclRefs.push_back(Exp);
5237 BlockByCopyDeclsPtrSet.insert(VD);
5238 BlockByCopyDecls.push_back(VD);
5240 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5241 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5242 BlockDeclRefs.push_back(Exp);
5243 BlockByRefDeclsPtrSet.insert(VD);
5244 BlockByRefDecls.push_back(VD);
5247 // Find any imported blocks...they will need special attention.
5248 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5249 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5250 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5251 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5252 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5254 InnerDeclRefsCount.push_back(countOfInnerDecls);
5256 std::string FuncName;
5259 FuncName = CurFunctionDef->getNameAsString();
5260 else if (CurMethodDef)
5261 BuildUniqueMethodName(FuncName, CurMethodDef);
5262 else if (GlobalVarDecl)
5263 FuncName = std::string(GlobalVarDecl->getNameAsString());
5265 bool GlobalBlockExpr =
5266 block->getDeclContext()->getRedeclContext()->isFileContext();
5268 if (GlobalBlockExpr && !GlobalVarDecl) {
5269 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5270 GlobalBlockExpr = false;
5273 std::string BlockNumber = utostr(Blocks.size()-1);
5275 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5277 // Get a pointer to the function type so we can cast appropriately.
5278 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5279 QualType FType = Context->getPointerType(BFT);
5284 // Simulate a contructor call...
5287 if (GlobalBlockExpr)
5291 Tag += FuncName + "_block_impl_" + BlockNumber;
5293 FD = SynthBlockInitFunctionDecl(Tag);
5294 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
5297 SmallVector<Expr*, 4> InitExprs;
5299 // Initialize the block function.
5300 FD = SynthBlockInitFunctionDecl(Func);
5301 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5302 VK_LValue, SourceLocation());
5303 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5305 InitExprs.push_back(castExpr);
5307 // Initialize the block descriptor.
5308 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5310 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5311 SourceLocation(), SourceLocation(),
5312 &Context->Idents.get(DescData.c_str()),
5313 Context->VoidPtrTy, 0,
5314 SC_Static, SC_None);
5315 UnaryOperator *DescRefExpr =
5316 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
5321 Context->getPointerType(Context->VoidPtrTy),
5322 VK_RValue, OK_Ordinary,
5324 InitExprs.push_back(DescRefExpr);
5326 // Add initializers for any closure decl refs.
5327 if (BlockDeclRefs.size()) {
5329 // Output all "by copy" declarations.
5330 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5331 E = BlockByCopyDecls.end(); I != E; ++I) {
5332 if (isObjCType((*I)->getType())) {
5333 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5334 FD = SynthBlockInitFunctionDecl((*I)->getName());
5335 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5336 VK_LValue, SourceLocation());
5337 if (HasLocalVariableExternalStorage(*I)) {
5338 QualType QT = (*I)->getType();
5339 QT = Context->getPointerType(QT);
5340 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5341 OK_Ordinary, SourceLocation());
5343 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5344 FD = SynthBlockInitFunctionDecl((*I)->getName());
5345 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5346 VK_LValue, SourceLocation());
5347 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5350 FD = SynthBlockInitFunctionDecl((*I)->getName());
5351 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5352 VK_LValue, SourceLocation());
5353 if (HasLocalVariableExternalStorage(*I)) {
5354 QualType QT = (*I)->getType();
5355 QT = Context->getPointerType(QT);
5356 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5357 OK_Ordinary, SourceLocation());
5361 InitExprs.push_back(Exp);
5363 // Output all "by ref" declarations.
5364 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5365 E = BlockByRefDecls.end(); I != E; ++I) {
5366 ValueDecl *ND = (*I);
5367 std::string Name(ND->getNameAsString());
5368 std::string RecName;
5369 RewriteByRefString(RecName, Name, ND, true);
5370 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5371 + sizeof("struct"));
5372 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5373 SourceLocation(), SourceLocation(),
5375 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5376 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5378 FD = SynthBlockInitFunctionDecl((*I)->getName());
5379 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
5381 bool isNestedCapturedVar = false;
5383 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5384 ce = block->capture_end(); ci != ce; ++ci) {
5385 const VarDecl *variable = ci->getVariable();
5386 if (variable == ND && ci->isNested()) {
5387 assert (ci->isByRef() &&
5388 "SynthBlockInitExpr - captured block variable is not byref");
5389 isNestedCapturedVar = true;
5393 // captured nested byref variable has its address passed. Do not take
5394 // its address again.
5395 if (!isNestedCapturedVar)
5396 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5397 Context->getPointerType(Exp->getType()),
5398 VK_RValue, OK_Ordinary, SourceLocation());
5399 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5400 InitExprs.push_back(Exp);
5403 if (ImportedBlockDecls.size()) {
5404 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5405 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5407 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5408 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5409 Context->IntTy, SourceLocation());
5410 InitExprs.push_back(FlagExp);
5412 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
5413 FType, VK_LValue, SourceLocation());
5415 if (GlobalBlockExpr) {
5416 assert (GlobalConstructionExp == 0 &&
5417 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5418 GlobalConstructionExp = NewRep;
5422 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5423 Context->getPointerType(NewRep->getType()),
5424 VK_RValue, OK_Ordinary, SourceLocation());
5425 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5427 BlockDeclRefs.clear();
5428 BlockByRefDecls.clear();
5429 BlockByRefDeclsPtrSet.clear();
5430 BlockByCopyDecls.clear();
5431 BlockByCopyDeclsPtrSet.clear();
5432 ImportedBlockDecls.clear();
5436 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5437 if (const ObjCForCollectionStmt * CS =
5438 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5439 return CS->getElement() == DS;
5443 //===----------------------------------------------------------------------===//
5444 // Function Body / Expression rewriting
5445 //===----------------------------------------------------------------------===//
5447 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5448 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5449 isa<DoStmt>(S) || isa<ForStmt>(S))
5451 else if (isa<ObjCForCollectionStmt>(S)) {
5453 ObjCBcLabelNo.push_back(++BcLabelCount);
5456 // Pseudo-object operations and ivar references need special
5457 // treatment because we're going to recursively rewrite them.
5458 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5459 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5460 return RewritePropertyOrImplicitSetter(PseudoOp);
5462 return RewritePropertyOrImplicitGetter(PseudoOp);
5464 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5465 return RewriteObjCIvarRefExpr(IvarRefExpr);
5468 SourceRange OrigStmtRange = S->getSourceRange();
5470 // Perform a bottom up rewrite of all children.
5471 for (Stmt::child_range CI = S->children(); CI; ++CI)
5473 Stmt *childStmt = (*CI);
5474 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5480 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5481 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5482 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5483 InnerContexts.insert(BE->getBlockDecl());
5484 ImportedLocalExternalDecls.clear();
5485 GetInnerBlockDeclRefExprs(BE->getBody(),
5486 InnerBlockDeclRefs, InnerContexts);
5487 // Rewrite the block body in place.
5488 Stmt *SaveCurrentBody = CurrentBody;
5489 CurrentBody = BE->getBody();
5491 // block literal on rhs of a property-dot-sytax assignment
5492 // must be replaced by its synthesize ast so getRewrittenText
5493 // works as expected. In this case, what actually ends up on RHS
5494 // is the blockTranscribed which is the helper function for the
5495 // block literal; as in: self.c = ^() {[ace ARR];};
5496 bool saveDisableReplaceStmt = DisableReplaceStmt;
5497 DisableReplaceStmt = false;
5498 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5499 DisableReplaceStmt = saveDisableReplaceStmt;
5500 CurrentBody = SaveCurrentBody;
5502 ImportedLocalExternalDecls.clear();
5503 // Now we snarf the rewritten text and stash it away for later use.
5504 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5505 RewrittenBlockExprs[BE] = Str;
5507 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5509 //blockTranscribed->dump();
5510 ReplaceStmt(S, blockTranscribed);
5511 return blockTranscribed;
5513 // Handle specific things.
5514 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5515 return RewriteAtEncode(AtEncode);
5517 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5518 return RewriteAtSelector(AtSelector);
5520 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5521 return RewriteObjCStringLiteral(AtString);
5523 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5524 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5526 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5527 return RewriteObjCBoxedExpr(BoxedExpr);
5529 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5530 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5532 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5533 dyn_cast<ObjCDictionaryLiteral>(S))
5534 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5536 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5538 // Before we rewrite it, put the original message expression in a comment.
5539 SourceLocation startLoc = MessExpr->getLocStart();
5540 SourceLocation endLoc = MessExpr->getLocEnd();
5542 const char *startBuf = SM->getCharacterData(startLoc);
5543 const char *endBuf = SM->getCharacterData(endLoc);
5545 std::string messString;
5546 messString += "// ";
5547 messString.append(startBuf, endBuf-startBuf+1);
5550 // FIXME: Missing definition of
5551 // InsertText(clang::SourceLocation, char const*, unsigned int).
5552 // InsertText(startLoc, messString.c_str(), messString.size());
5553 // Tried this, but it didn't work either...
5554 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5556 return RewriteMessageExpr(MessExpr);
5559 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5560 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5561 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5564 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5565 return RewriteObjCTryStmt(StmtTry);
5567 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5568 return RewriteObjCSynchronizedStmt(StmtTry);
5570 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5571 return RewriteObjCThrowStmt(StmtThrow);
5573 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5574 return RewriteObjCProtocolExpr(ProtocolExp);
5576 if (ObjCForCollectionStmt *StmtForCollection =
5577 dyn_cast<ObjCForCollectionStmt>(S))
5578 return RewriteObjCForCollectionStmt(StmtForCollection,
5579 OrigStmtRange.getEnd());
5580 if (BreakStmt *StmtBreakStmt =
5581 dyn_cast<BreakStmt>(S))
5582 return RewriteBreakStmt(StmtBreakStmt);
5583 if (ContinueStmt *StmtContinueStmt =
5584 dyn_cast<ContinueStmt>(S))
5585 return RewriteContinueStmt(StmtContinueStmt);
5587 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5589 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5590 // FIXME: What we're doing here is modifying the type-specifier that
5591 // precedes the first Decl. In the future the DeclGroup should have
5592 // a separate type-specifier that we can rewrite.
5593 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5594 // the context of an ObjCForCollectionStmt. For example:
5595 // NSArray *someArray;
5596 // for (id <FooProtocol> index in someArray) ;
5597 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5598 // and it depends on the original text locations/positions.
5599 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5600 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5602 // Blocks rewrite rules.
5603 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5606 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5607 if (isTopLevelBlockPointerType(ND->getType()))
5608 RewriteBlockPointerDecl(ND);
5609 else if (ND->getType()->isFunctionPointerType())
5610 CheckFunctionPointerDecl(ND->getType(), ND);
5611 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5612 if (VD->hasAttr<BlocksAttr>()) {
5613 static unsigned uniqueByrefDeclCount = 0;
5614 assert(!BlockByRefDeclNo.count(ND) &&
5615 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5616 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5617 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5620 RewriteTypeOfDecl(VD);
5623 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5624 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5625 RewriteBlockPointerDecl(TD);
5626 else if (TD->getUnderlyingType()->isFunctionPointerType())
5627 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5632 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5633 RewriteObjCQualifiedInterfaceTypes(CE);
5635 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5636 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5637 assert(!Stmts.empty() && "Statement stack is empty");
5638 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5639 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5640 && "Statement stack mismatch");
5643 // Handle blocks rewriting.
5644 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5645 ValueDecl *VD = DRE->getDecl();
5646 if (VD->hasAttr<BlocksAttr>())
5647 return RewriteBlockDeclRefExpr(DRE);
5648 if (HasLocalVariableExternalStorage(VD))
5649 return RewriteLocalVariableExternalStorage(DRE);
5652 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5653 if (CE->getCallee()->getType()->isBlockPointerType()) {
5654 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5655 ReplaceStmt(S, BlockCall);
5659 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5660 RewriteCastExpr(CE);
5662 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5663 RewriteImplicitCastObjCExpr(ICE);
5667 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5668 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5671 // Get the new text.
5673 llvm::raw_string_ostream Buf(SStr);
5674 Replacement->printPretty(Buf);
5675 const std::string &Str = Buf.str();
5677 printf("CAST = %s\n", &Str[0]);
5678 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5683 // Return this stmt unmodified.
5687 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5688 for (RecordDecl::field_iterator i = RD->field_begin(),
5689 e = RD->field_end(); i != e; ++i) {
5691 if (isTopLevelBlockPointerType(FD->getType()))
5692 RewriteBlockPointerDecl(FD);
5693 if (FD->getType()->isObjCQualifiedIdType() ||
5694 FD->getType()->isObjCQualifiedInterfaceType())
5695 RewriteObjCQualifiedInterfaceTypes(FD);
5699 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5700 /// main file of the input.
5701 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5702 switch (D->getKind()) {
5703 case Decl::Function: {
5704 FunctionDecl *FD = cast<FunctionDecl>(D);
5705 if (FD->isOverloadedOperator())
5708 // Since function prototypes don't have ParmDecl's, we check the function
5709 // prototype. This enables us to rewrite function declarations and
5710 // definitions using the same code.
5711 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5713 if (!FD->isThisDeclarationADefinition())
5716 // FIXME: If this should support Obj-C++, support CXXTryStmt
5717 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5718 CurFunctionDef = FD;
5721 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5724 if (PropParentMap) {
5725 delete PropParentMap;
5728 // This synthesizes and inserts the block "impl" struct, invoke function,
5729 // and any copy/dispose helper functions.
5730 InsertBlockLiteralsWithinFunction(FD);
5731 RewriteLineDirective(D);
5736 case Decl::ObjCMethod: {
5737 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5738 if (CompoundStmt *Body = MD->getCompoundBody()) {
5742 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5745 if (PropParentMap) {
5746 delete PropParentMap;
5749 InsertBlockLiteralsWithinMethod(MD);
5750 RewriteLineDirective(D);
5755 case Decl::ObjCImplementation: {
5756 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5757 ClassImplementation.push_back(CI);
5760 case Decl::ObjCCategoryImpl: {
5761 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5762 CategoryImplementation.push_back(CI);
5766 VarDecl *VD = cast<VarDecl>(D);
5767 RewriteObjCQualifiedInterfaceTypes(VD);
5768 if (isTopLevelBlockPointerType(VD->getType()))
5769 RewriteBlockPointerDecl(VD);
5770 else if (VD->getType()->isFunctionPointerType()) {
5771 CheckFunctionPointerDecl(VD->getType(), VD);
5772 if (VD->getInit()) {
5773 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5774 RewriteCastExpr(CE);
5777 } else if (VD->getType()->isRecordType()) {
5778 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5779 if (RD->isCompleteDefinition())
5780 RewriteRecordBody(RD);
5782 if (VD->getInit()) {
5784 CurrentBody = VD->getInit();
5785 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5787 if (PropParentMap) {
5788 delete PropParentMap;
5791 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5794 // This is needed for blocks.
5795 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5796 RewriteCastExpr(CE);
5801 case Decl::TypeAlias:
5802 case Decl::Typedef: {
5803 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5804 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5805 RewriteBlockPointerDecl(TD);
5806 else if (TD->getUnderlyingType()->isFunctionPointerType())
5807 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5811 case Decl::CXXRecord:
5812 case Decl::Record: {
5813 RecordDecl *RD = cast<RecordDecl>(D);
5814 if (RD->isCompleteDefinition())
5815 RewriteRecordBody(RD);
5824 /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5825 /// protocol reference symbols in the for of:
5826 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5827 static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5828 ObjCProtocolDecl *PDecl,
5829 std::string &Result) {
5830 // Also output .objc_protorefs$B section and its meta-data.
5831 if (Context->getLangOpts().MicrosoftExt)
5832 Result += "static ";
5833 Result += "struct _protocol_t *";
5834 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5835 Result += PDecl->getNameAsString();
5837 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5841 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5842 if (Diags.hasErrorOccurred())
5847 // Here's a great place to add any extra declarations that may be needed.
5848 // Write out meta data for each @protocol(<expr>).
5849 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5850 E = ProtocolExprDecls.end(); I != E; ++I) {
5851 RewriteObjCProtocolMetaData(*I, Preamble);
5852 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5855 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5857 if (ClassImplementation.size() || CategoryImplementation.size())
5858 RewriteImplementations();
5860 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5861 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5862 // Write struct declaration for the class matching its ivar declarations.
5863 // Note that for modern abi, this is postponed until the end of TU
5864 // because class extensions and the implementation might declare their own
5866 RewriteInterfaceDecl(CDecl);
5869 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5871 if (const RewriteBuffer *RewriteBuf =
5872 Rewrite.getRewriteBufferFor(MainFileID)) {
5873 //printf("Changed:\n");
5874 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5876 llvm::errs() << "No changes\n";
5879 if (ClassImplementation.size() || CategoryImplementation.size() ||
5880 ProtocolExprDecls.size()) {
5881 // Rewrite Objective-c meta data*
5882 std::string ResultStr;
5883 RewriteMetaDataIntoBuffer(ResultStr);
5885 *OutFile << ResultStr;
5889 std::string ResultStr;
5890 WriteImageInfo(ResultStr);
5891 *OutFile << ResultStr;
5896 void RewriteModernObjC::Initialize(ASTContext &context) {
5897 InitializeCommon(context);
5899 Preamble += "#ifndef __OBJC2__\n";
5900 Preamble += "#define __OBJC2__\n";
5901 Preamble += "#endif\n";
5903 // declaring objc_selector outside the parameter list removes a silly
5904 // scope related warning...
5906 Preamble = "#pragma once\n";
5907 Preamble += "struct objc_selector; struct objc_class;\n";
5908 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5909 Preamble += "\n\tstruct objc_object *superClass; ";
5910 // Add a constructor for creating temporary objects.
5911 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5912 Preamble += ": object(o), superClass(s) {} ";
5913 Preamble += "\n};\n";
5915 if (LangOpts.MicrosoftExt) {
5916 // Define all sections using syntax that makes sense.
5917 // These are currently generated.
5918 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5919 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5920 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5921 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5922 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5923 // These are generated but not necessary for functionality.
5924 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5925 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5926 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5927 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5929 // These need be generated for performance. Currently they are not,
5930 // using API calls instead.
5931 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5932 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5933 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5936 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5937 Preamble += "typedef struct objc_object Protocol;\n";
5938 Preamble += "#define _REWRITER_typedef_Protocol\n";
5939 Preamble += "#endif\n";
5940 if (LangOpts.MicrosoftExt) {
5941 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5942 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5945 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5947 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5948 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5949 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5950 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5951 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5953 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5954 Preamble += "(const char *);\n";
5955 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5956 Preamble += "(struct objc_class *);\n";
5957 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5958 Preamble += "(const char *);\n";
5959 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5960 // @synchronized hooks.
5961 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5962 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5963 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5964 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5965 Preamble += "struct __objcFastEnumerationState {\n\t";
5966 Preamble += "unsigned long state;\n\t";
5967 Preamble += "void **itemsPtr;\n\t";
5968 Preamble += "unsigned long *mutationsPtr;\n\t";
5969 Preamble += "unsigned long extra[5];\n};\n";
5970 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5971 Preamble += "#define __FASTENUMERATIONSTATE\n";
5972 Preamble += "#endif\n";
5973 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5974 Preamble += "struct __NSConstantStringImpl {\n";
5975 Preamble += " int *isa;\n";
5976 Preamble += " int flags;\n";
5977 Preamble += " char *str;\n";
5978 Preamble += " long length;\n";
5980 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5981 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5982 Preamble += "#else\n";
5983 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5984 Preamble += "#endif\n";
5985 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5986 Preamble += "#endif\n";
5988 Preamble += "#ifndef BLOCK_IMPL\n";
5989 Preamble += "#define BLOCK_IMPL\n";
5990 Preamble += "struct __block_impl {\n";
5991 Preamble += " void *isa;\n";
5992 Preamble += " int Flags;\n";
5993 Preamble += " int Reserved;\n";
5994 Preamble += " void *FuncPtr;\n";
5996 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5997 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5998 Preamble += "extern \"C\" __declspec(dllexport) "
5999 "void _Block_object_assign(void *, const void *, const int);\n";
6000 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6001 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6002 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6003 Preamble += "#else\n";
6004 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6005 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6006 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6007 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6008 Preamble += "#endif\n";
6009 Preamble += "#endif\n";
6010 if (LangOpts.MicrosoftExt) {
6011 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6012 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6013 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6014 Preamble += "#define __attribute__(X)\n";
6015 Preamble += "#endif\n";
6016 Preamble += "#ifndef __weak\n";
6017 Preamble += "#define __weak\n";
6018 Preamble += "#endif\n";
6019 Preamble += "#ifndef __block\n";
6020 Preamble += "#define __block\n";
6021 Preamble += "#endif\n";
6024 Preamble += "#define __block\n";
6025 Preamble += "#define __weak\n";
6028 // Declarations required for modern objective-c array and dictionary literals.
6029 Preamble += "\n#include <stdarg.h>\n";
6030 Preamble += "struct __NSContainer_literal {\n";
6031 Preamble += " void * *arr;\n";
6032 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
6033 Preamble += "\tva_list marker;\n";
6034 Preamble += "\tva_start(marker, count);\n";
6035 Preamble += "\tarr = new void *[count];\n";
6036 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6037 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6038 Preamble += "\tva_end( marker );\n";
6039 Preamble += " };\n";
6040 Preamble += " ~__NSContainer_literal() {\n";
6041 Preamble += "\tdelete[] arr;\n";
6045 // Declaration required for implementation of @autoreleasepool statement.
6046 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6047 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6048 Preamble += "struct __AtAutoreleasePool {\n";
6049 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6050 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6051 Preamble += " void * atautoreleasepoolobj;\n";
6054 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6055 // as this avoids warning in any 64bit/32bit compilation model.
6056 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6059 /// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6061 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6062 std::string &Result) {
6063 if (ivar->isBitField()) {
6064 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6065 // place all bitfields at offset 0.
6068 Result += "__OFFSETOFIVAR__(struct ";
6069 Result += ivar->getContainingInterface()->getNameAsString();
6070 if (LangOpts.MicrosoftExt)
6073 Result += ivar->getNameAsString();
6078 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6079 /// struct _prop_t {
6080 /// const char *name;
6081 /// char *attributes;
6084 /// struct _prop_list_t {
6085 /// uint32_t entsize; // sizeof(struct _prop_t)
6086 /// uint32_t count_of_properties;
6087 /// struct _prop_t prop_list[count_of_properties];
6090 /// struct _protocol_t;
6092 /// struct _protocol_list_t {
6093 /// long protocol_count; // Note, this is 32/64 bit
6094 /// struct _protocol_t * protocol_list[protocol_count];
6097 /// struct _objc_method {
6099 /// const char *method_type;
6103 /// struct _method_list_t {
6104 /// uint32_t entsize; // sizeof(struct _objc_method)
6105 /// uint32_t method_count;
6106 /// struct _objc_method method_list[method_count];
6109 /// struct _protocol_t {
6111 /// const char *protocol_name;
6112 /// const struct _protocol_list_t * protocol_list; // super protocols
6113 /// const struct method_list_t *instance_methods;
6114 /// const struct method_list_t *class_methods;
6115 /// const struct method_list_t *optionalInstanceMethods;
6116 /// const struct method_list_t *optionalClassMethods;
6117 /// const struct _prop_list_t * properties;
6118 /// const uint32_t size; // sizeof(struct _protocol_t)
6119 /// const uint32_t flags; // = 0
6120 /// const char ** extendedMethodTypes;
6123 /// struct _ivar_t {
6124 /// unsigned long int *offset; // pointer to ivar offset location
6125 /// const char *name;
6126 /// const char *type;
6127 /// uint32_t alignment;
6131 /// struct _ivar_list_t {
6132 /// uint32 entsize; // sizeof(struct _ivar_t)
6134 /// struct _ivar_t list[count];
6137 /// struct _class_ro_t {
6139 /// uint32_t instanceStart;
6140 /// uint32_t instanceSize;
6141 /// uint32_t reserved; // only when building for 64bit targets
6142 /// const uint8_t *ivarLayout;
6143 /// const char *name;
6144 /// const struct _method_list_t *baseMethods;
6145 /// const struct _protocol_list_t *baseProtocols;
6146 /// const struct _ivar_list_t *ivars;
6147 /// const uint8_t *weakIvarLayout;
6148 /// const struct _prop_list_t *properties;
6151 /// struct _class_t {
6152 /// struct _class_t *isa;
6153 /// struct _class_t *superclass;
6156 /// struct _class_ro_t *ro;
6159 /// struct _category_t {
6160 /// const char *name;
6161 /// struct _class_t *cls;
6162 /// const struct _method_list_t *instance_methods;
6163 /// const struct _method_list_t *class_methods;
6164 /// const struct _protocol_list_t *protocols;
6165 /// const struct _prop_list_t *properties;
6168 /// MessageRefTy - LLVM for:
6169 /// struct _message_ref_t {
6174 /// SuperMessageRefTy - LLVM for:
6175 /// struct _super_message_ref_t {
6176 /// SUPER_IMP messenger;
6180 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6181 static bool meta_data_declared = false;
6182 if (meta_data_declared)
6185 Result += "\nstruct _prop_t {\n";
6186 Result += "\tconst char *name;\n";
6187 Result += "\tconst char *attributes;\n";
6190 Result += "\nstruct _protocol_t;\n";
6192 Result += "\nstruct _objc_method {\n";
6193 Result += "\tstruct objc_selector * _cmd;\n";
6194 Result += "\tconst char *method_type;\n";
6195 Result += "\tvoid *_imp;\n";
6198 Result += "\nstruct _protocol_t {\n";
6199 Result += "\tvoid * isa; // NULL\n";
6200 Result += "\tconst char *protocol_name;\n";
6201 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6202 Result += "\tconst struct method_list_t *instance_methods;\n";
6203 Result += "\tconst struct method_list_t *class_methods;\n";
6204 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6205 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6206 Result += "\tconst struct _prop_list_t * properties;\n";
6207 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6208 Result += "\tconst unsigned int flags; // = 0\n";
6209 Result += "\tconst char ** extendedMethodTypes;\n";
6212 Result += "\nstruct _ivar_t {\n";
6213 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
6214 Result += "\tconst char *name;\n";
6215 Result += "\tconst char *type;\n";
6216 Result += "\tunsigned int alignment;\n";
6217 Result += "\tunsigned int size;\n";
6220 Result += "\nstruct _class_ro_t {\n";
6221 Result += "\tunsigned int flags;\n";
6222 Result += "\tunsigned int instanceStart;\n";
6223 Result += "\tunsigned int instanceSize;\n";
6224 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6225 if (Triple.getArch() == llvm::Triple::x86_64)
6226 Result += "\tunsigned int reserved;\n";
6227 Result += "\tconst unsigned char *ivarLayout;\n";
6228 Result += "\tconst char *name;\n";
6229 Result += "\tconst struct _method_list_t *baseMethods;\n";
6230 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6231 Result += "\tconst struct _ivar_list_t *ivars;\n";
6232 Result += "\tconst unsigned char *weakIvarLayout;\n";
6233 Result += "\tconst struct _prop_list_t *properties;\n";
6236 Result += "\nstruct _class_t {\n";
6237 Result += "\tstruct _class_t *isa;\n";
6238 Result += "\tstruct _class_t *superclass;\n";
6239 Result += "\tvoid *cache;\n";
6240 Result += "\tvoid *vtable;\n";
6241 Result += "\tstruct _class_ro_t *ro;\n";
6244 Result += "\nstruct _category_t {\n";
6245 Result += "\tconst char *name;\n";
6246 Result += "\tstruct _class_t *cls;\n";
6247 Result += "\tconst struct _method_list_t *instance_methods;\n";
6248 Result += "\tconst struct _method_list_t *class_methods;\n";
6249 Result += "\tconst struct _protocol_list_t *protocols;\n";
6250 Result += "\tconst struct _prop_list_t *properties;\n";
6253 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6254 Result += "#pragma warning(disable:4273)\n";
6255 meta_data_declared = true;
6258 static void Write_protocol_list_t_TypeDecl(std::string &Result,
6259 long super_protocol_count) {
6260 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6261 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6262 Result += "\tstruct _protocol_t *super_protocols[";
6263 Result += utostr(super_protocol_count); Result += "];\n";
6267 static void Write_method_list_t_TypeDecl(std::string &Result,
6268 unsigned int method_count) {
6269 Result += "struct /*_method_list_t*/"; Result += " {\n";
6270 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6271 Result += "\tunsigned int method_count;\n";
6272 Result += "\tstruct _objc_method method_list[";
6273 Result += utostr(method_count); Result += "];\n";
6277 static void Write__prop_list_t_TypeDecl(std::string &Result,
6278 unsigned int property_count) {
6279 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6280 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6281 Result += "\tunsigned int count_of_properties;\n";
6282 Result += "\tstruct _prop_t prop_list[";
6283 Result += utostr(property_count); Result += "];\n";
6287 static void Write__ivar_list_t_TypeDecl(std::string &Result,
6288 unsigned int ivar_count) {
6289 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6290 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6291 Result += "\tunsigned int count;\n";
6292 Result += "\tstruct _ivar_t ivar_list[";
6293 Result += utostr(ivar_count); Result += "];\n";
6297 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6298 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6300 StringRef ProtocolName) {
6301 if (SuperProtocols.size() > 0) {
6302 Result += "\nstatic ";
6303 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6304 Result += " "; Result += VarName;
6305 Result += ProtocolName;
6306 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6307 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6308 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6309 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6310 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6311 Result += SuperPD->getNameAsString();
6320 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6321 ASTContext *Context, std::string &Result,
6322 ArrayRef<ObjCMethodDecl *> Methods,
6324 StringRef TopLevelDeclName,
6326 if (Methods.size() > 0) {
6327 Result += "\nstatic ";
6328 Write_method_list_t_TypeDecl(Result, Methods.size());
6329 Result += " "; Result += VarName;
6330 Result += TopLevelDeclName;
6331 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6332 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6333 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6334 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6335 ObjCMethodDecl *MD = Methods[i];
6337 Result += "\t{{(struct objc_selector *)\"";
6339 Result += "\t{(struct objc_selector *)\"";
6340 Result += (MD)->getSelector().getAsString(); Result += "\"";
6342 std::string MethodTypeString;
6343 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6344 Result += "\""; Result += MethodTypeString; Result += "\"";
6349 Result += "(void *)";
6350 Result += RewriteObj.MethodInternalNames[MD];
6361 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6362 ASTContext *Context, std::string &Result,
6363 ArrayRef<ObjCPropertyDecl *> Properties,
6364 const Decl *Container,
6366 StringRef ProtocolName) {
6367 if (Properties.size() > 0) {
6368 Result += "\nstatic ";
6369 Write__prop_list_t_TypeDecl(Result, Properties.size());
6370 Result += " "; Result += VarName;
6371 Result += ProtocolName;
6372 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6373 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6374 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6375 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6376 ObjCPropertyDecl *PropDecl = Properties[i];
6381 Result += PropDecl->getName(); Result += "\",";
6382 std::string PropertyTypeString, QuotePropertyTypeString;
6383 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6384 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6385 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6396 enum MetaDataDlags {
6400 OBJC2_CLS_HIDDEN = 0x10,
6401 CLS_EXCEPTION = 0x20,
6403 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6404 CLS_HAS_IVAR_RELEASER = 0x40,
6405 /// class was compiled with -fobjc-arr
6406 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6409 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6411 const std::string &InstanceStart,
6412 const std::string &InstanceSize,
6413 ArrayRef<ObjCMethodDecl *>baseMethods,
6414 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6415 ArrayRef<ObjCIvarDecl *>ivars,
6416 ArrayRef<ObjCPropertyDecl *>Properties,
6418 StringRef ClassName) {
6419 Result += "\nstatic struct _class_ro_t ";
6420 Result += VarName; Result += ClassName;
6421 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6423 Result += llvm::utostr(flags); Result += ", ";
6424 Result += InstanceStart; Result += ", ";
6425 Result += InstanceSize; Result += ", \n";
6427 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6428 if (Triple.getArch() == llvm::Triple::x86_64)
6429 // uint32_t const reserved; // only when building for 64bit targets
6430 Result += "(unsigned int)0, \n\t";
6431 // const uint8_t * const ivarLayout;
6432 Result += "0, \n\t";
6433 Result += "\""; Result += ClassName; Result += "\",\n\t";
6434 bool metaclass = ((flags & CLS_META) != 0);
6435 if (baseMethods.size() > 0) {
6436 Result += "(const struct _method_list_t *)&";
6438 Result += "_OBJC_$_CLASS_METHODS_";
6440 Result += "_OBJC_$_INSTANCE_METHODS_";
6441 Result += ClassName;
6445 Result += "0, \n\t";
6447 if (!metaclass && baseProtocols.size() > 0) {
6448 Result += "(const struct _objc_protocol_list *)&";
6449 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6453 Result += "0, \n\t";
6455 if (!metaclass && ivars.size() > 0) {
6456 Result += "(const struct _ivar_list_t *)&";
6457 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6461 Result += "0, \n\t";
6464 Result += "0, \n\t";
6465 if (!metaclass && Properties.size() > 0) {
6466 Result += "(const struct _prop_list_t *)&";
6467 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6476 static void Write_class_t(ASTContext *Context, std::string &Result,
6478 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6479 bool rootClass = (!CDecl->getSuperClass());
6480 const ObjCInterfaceDecl *RootClass = CDecl;
6483 // Find the Root class
6484 RootClass = CDecl->getSuperClass();
6485 while (RootClass->getSuperClass()) {
6486 RootClass = RootClass->getSuperClass();
6490 if (metaclass && rootClass) {
6491 // Need to handle a case of use of forward declaration.
6493 Result += "extern \"C\" ";
6494 if (CDecl->getImplementation())
6495 Result += "__declspec(dllexport) ";
6497 Result += "__declspec(dllimport) ";
6499 Result += "struct _class_t OBJC_CLASS_$_";
6500 Result += CDecl->getNameAsString();
6503 // Also, for possibility of 'super' metadata class not having been defined yet.
6505 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6507 Result += "extern \"C\" ";
6508 if (SuperClass->getImplementation())
6509 Result += "__declspec(dllexport) ";
6511 Result += "__declspec(dllimport) ";
6513 Result += "struct _class_t ";
6515 Result += SuperClass->getNameAsString();
6518 if (metaclass && RootClass != SuperClass) {
6519 Result += "extern \"C\" ";
6520 if (RootClass->getImplementation())
6521 Result += "__declspec(dllexport) ";
6523 Result += "__declspec(dllimport) ";
6525 Result += "struct _class_t ";
6527 Result += RootClass->getNameAsString();
6532 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6533 Result += VarName; Result += CDecl->getNameAsString();
6534 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6538 Result += "0, // &"; Result += VarName;
6539 Result += RootClass->getNameAsString();
6541 Result += "0, // &"; Result += VarName;
6542 Result += CDecl->getSuperClass()->getNameAsString();
6546 Result += "0, // &"; Result += VarName;
6547 Result += CDecl->getNameAsString();
6549 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6554 Result += "0, // &OBJC_METACLASS_$_";
6555 Result += CDecl->getNameAsString();
6558 Result += "0, // &"; Result += VarName;
6559 Result += CDecl->getSuperClass()->getNameAsString();
6565 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6566 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6568 Result += "&_OBJC_METACLASS_RO_$_";
6570 Result += "&_OBJC_CLASS_RO_$_";
6571 Result += CDecl->getNameAsString();
6572 Result += ",\n};\n";
6574 // Add static function to initialize some of the meta-data fields.
6575 // avoid doing it twice.
6579 const ObjCInterfaceDecl *SuperClass =
6580 rootClass ? CDecl : CDecl->getSuperClass();
6582 Result += "static void OBJC_CLASS_SETUP_$_";
6583 Result += CDecl->getNameAsString();
6584 Result += "(void ) {\n";
6585 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6586 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6587 Result += RootClass->getNameAsString(); Result += ";\n";
6589 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6590 Result += ".superclass = ";
6592 Result += "&OBJC_CLASS_$_";
6594 Result += "&OBJC_METACLASS_$_";
6596 Result += SuperClass->getNameAsString(); Result += ";\n";
6598 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6599 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6601 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6602 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6603 Result += CDecl->getNameAsString(); Result += ";\n";
6606 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6607 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6608 Result += SuperClass->getNameAsString(); Result += ";\n";
6611 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6612 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6616 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6617 std::string &Result,
6618 ObjCCategoryDecl *CatDecl,
6619 ObjCInterfaceDecl *ClassDecl,
6620 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6621 ArrayRef<ObjCMethodDecl *> ClassMethods,
6622 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6623 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6624 StringRef CatName = CatDecl->getName();
6625 StringRef ClassName = ClassDecl->getName();
6626 // must declare an extern class object in case this class is not implemented
6629 Result += "extern \"C\" ";
6630 if (ClassDecl->getImplementation())
6631 Result += "__declspec(dllexport) ";
6633 Result += "__declspec(dllimport) ";
6635 Result += "struct _class_t ";
6636 Result += "OBJC_CLASS_$_"; Result += ClassName;
6639 Result += "\nstatic struct _category_t ";
6640 Result += "_OBJC_$_CATEGORY_";
6641 Result += ClassName; Result += "_$_"; Result += CatName;
6642 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6644 Result += "\t\""; Result += ClassName; Result += "\",\n";
6645 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6647 if (InstanceMethods.size() > 0) {
6648 Result += "\t(const struct _method_list_t *)&";
6649 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6650 Result += ClassName; Result += "_$_"; Result += CatName;
6656 if (ClassMethods.size() > 0) {
6657 Result += "\t(const struct _method_list_t *)&";
6658 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6659 Result += ClassName; Result += "_$_"; Result += CatName;
6665 if (RefedProtocols.size() > 0) {
6666 Result += "\t(const struct _protocol_list_t *)&";
6667 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6668 Result += ClassName; Result += "_$_"; Result += CatName;
6674 if (ClassProperties.size() > 0) {
6675 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6676 Result += ClassName; Result += "_$_"; Result += CatName;
6684 // Add static function to initialize the class pointer in the category structure.
6685 Result += "static void OBJC_CATEGORY_SETUP_$_";
6686 Result += ClassDecl->getNameAsString();
6689 Result += "(void ) {\n";
6690 Result += "\t_OBJC_$_CATEGORY_";
6691 Result += ClassDecl->getNameAsString();
6694 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6698 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6699 ASTContext *Context, std::string &Result,
6700 ArrayRef<ObjCMethodDecl *> Methods,
6702 StringRef ProtocolName) {
6703 if (Methods.size() == 0)
6706 Result += "\nstatic const char *";
6707 Result += VarName; Result += ProtocolName;
6708 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6710 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6711 ObjCMethodDecl *MD = Methods[i];
6712 std::string MethodTypeString, QuoteMethodTypeString;
6713 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6714 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6715 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6724 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6725 ASTContext *Context,
6726 std::string &Result,
6727 ArrayRef<ObjCIvarDecl *> Ivars,
6728 ObjCInterfaceDecl *CDecl) {
6729 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6730 // this is what happens:
6732 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6733 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6734 Class->getVisibility() == HiddenVisibility)
6735 Visibility shoud be: HiddenVisibility;
6737 Visibility shoud be: DefaultVisibility;
6741 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6742 ObjCIvarDecl *IvarDecl = Ivars[i];
6743 if (Context->getLangOpts().MicrosoftExt)
6744 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6746 if (!Context->getLangOpts().MicrosoftExt ||
6747 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6748 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6749 Result += "extern \"C\" unsigned long int ";
6751 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6752 WriteInternalIvarName(CDecl, IvarDecl, Result);
6753 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6755 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6760 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6761 ASTContext *Context, std::string &Result,
6762 ArrayRef<ObjCIvarDecl *> Ivars,
6764 ObjCInterfaceDecl *CDecl) {
6765 if (Ivars.size() > 0) {
6766 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
6768 Result += "\nstatic ";
6769 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6770 Result += " "; Result += VarName;
6771 Result += CDecl->getNameAsString();
6772 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6773 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6774 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6775 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6776 ObjCIvarDecl *IvarDecl = Ivars[i];
6781 Result += "(unsigned long int *)&";
6782 WriteInternalIvarName(CDecl, IvarDecl, Result);
6785 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6786 std::string IvarTypeString, QuoteIvarTypeString;
6787 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6789 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6790 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6792 // FIXME. this alignment represents the host alignment and need be changed to
6793 // represent the target alignment.
6794 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6795 Align = llvm::Log2_32(Align);
6796 Result += llvm::utostr(Align); Result += ", ";
6797 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6798 Result += llvm::utostr(Size.getQuantity());
6808 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6809 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6810 std::string &Result) {
6812 // Do not synthesize the protocol more than once.
6813 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6815 WriteModernMetadataDeclarations(Context, Result);
6817 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6819 // Must write out all protocol definitions in current qualifier list,
6820 // and in their nested qualifiers before writing out current definition.
6821 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6822 E = PDecl->protocol_end(); I != E; ++I)
6823 RewriteObjCProtocolMetaData(*I, Result);
6825 // Construct method lists.
6826 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6827 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6828 for (ObjCProtocolDecl::instmeth_iterator
6829 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6831 ObjCMethodDecl *MD = *I;
6832 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6833 OptInstanceMethods.push_back(MD);
6835 InstanceMethods.push_back(MD);
6839 for (ObjCProtocolDecl::classmeth_iterator
6840 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6842 ObjCMethodDecl *MD = *I;
6843 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6844 OptClassMethods.push_back(MD);
6846 ClassMethods.push_back(MD);
6849 std::vector<ObjCMethodDecl *> AllMethods;
6850 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6851 AllMethods.push_back(InstanceMethods[i]);
6852 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6853 AllMethods.push_back(ClassMethods[i]);
6854 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6855 AllMethods.push_back(OptInstanceMethods[i]);
6856 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6857 AllMethods.push_back(OptClassMethods[i]);
6859 Write__extendedMethodTypes_initializer(*this, Context, Result,
6861 "_OBJC_PROTOCOL_METHOD_TYPES_",
6862 PDecl->getNameAsString());
6863 // Protocol's super protocol list
6864 std::vector<ObjCProtocolDecl *> SuperProtocols;
6865 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6866 E = PDecl->protocol_end(); I != E; ++I)
6867 SuperProtocols.push_back(*I);
6869 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6870 "_OBJC_PROTOCOL_REFS_",
6871 PDecl->getNameAsString());
6873 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6874 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6875 PDecl->getNameAsString(), false);
6877 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6878 "_OBJC_PROTOCOL_CLASS_METHODS_",
6879 PDecl->getNameAsString(), false);
6881 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6882 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6883 PDecl->getNameAsString(), false);
6885 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6886 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6887 PDecl->getNameAsString(), false);
6889 // Protocol's property metadata.
6890 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6891 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6892 E = PDecl->prop_end(); I != E; ++I)
6893 ProtocolProperties.push_back(*I);
6895 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6897 "_OBJC_PROTOCOL_PROPERTIES_",
6898 PDecl->getNameAsString());
6900 // Writer out root metadata for current protocol: struct _protocol_t
6902 if (LangOpts.MicrosoftExt)
6903 Result += "static ";
6904 Result += "struct _protocol_t _OBJC_PROTOCOL_";
6905 Result += PDecl->getNameAsString();
6906 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6907 Result += "\t0,\n"; // id is; is null
6908 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6909 if (SuperProtocols.size() > 0) {
6910 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6911 Result += PDecl->getNameAsString(); Result += ",\n";
6915 if (InstanceMethods.size() > 0) {
6916 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6917 Result += PDecl->getNameAsString(); Result += ",\n";
6922 if (ClassMethods.size() > 0) {
6923 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6924 Result += PDecl->getNameAsString(); Result += ",\n";
6929 if (OptInstanceMethods.size() > 0) {
6930 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6931 Result += PDecl->getNameAsString(); Result += ",\n";
6936 if (OptClassMethods.size() > 0) {
6937 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6938 Result += PDecl->getNameAsString(); Result += ",\n";
6943 if (ProtocolProperties.size() > 0) {
6944 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6945 Result += PDecl->getNameAsString(); Result += ",\n";
6950 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6953 if (AllMethods.size() > 0) {
6954 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6955 Result += PDecl->getNameAsString();
6959 Result += "\t0\n};\n";
6961 if (LangOpts.MicrosoftExt)
6962 Result += "static ";
6963 Result += "struct _protocol_t *";
6964 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6965 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6968 // Mark this protocol as having been generated.
6969 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6970 llvm_unreachable("protocol already synthesized");
6974 void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6975 const ObjCList<ObjCProtocolDecl> &Protocols,
6976 StringRef prefix, StringRef ClassName,
6977 std::string &Result) {
6978 if (Protocols.empty()) return;
6980 for (unsigned i = 0; i != Protocols.size(); i++)
6981 RewriteObjCProtocolMetaData(Protocols[i], Result);
6983 // Output the top lovel protocol meta-data for the class.
6984 /* struct _objc_protocol_list {
6985 struct _objc_protocol_list *next;
6987 struct _objc_protocol *class_protocols[];
6991 if (LangOpts.MicrosoftExt)
6992 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6993 Result += "static struct {\n";
6994 Result += "\tstruct _objc_protocol_list *next;\n";
6995 Result += "\tint protocol_count;\n";
6996 Result += "\tstruct _objc_protocol *class_protocols[";
6997 Result += utostr(Protocols.size());
6998 Result += "];\n} _OBJC_";
7000 Result += "_PROTOCOLS_";
7001 Result += ClassName;
7002 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7004 Result += utostr(Protocols.size());
7007 Result += "\t,{&_OBJC_PROTOCOL_";
7008 Result += Protocols[0]->getNameAsString();
7011 for (unsigned i = 1; i != Protocols.size(); i++) {
7012 Result += "\t ,&_OBJC_PROTOCOL_";
7013 Result += Protocols[i]->getNameAsString();
7016 Result += "\t }\n};\n";
7019 /// hasObjCExceptionAttribute - Return true if this class or any super
7020 /// class has the __objc_exception__ attribute.
7021 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7022 static bool hasObjCExceptionAttribute(ASTContext &Context,
7023 const ObjCInterfaceDecl *OID) {
7024 if (OID->hasAttr<ObjCExceptionAttr>())
7026 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7027 return hasObjCExceptionAttribute(Context, Super);
7031 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7032 std::string &Result) {
7033 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7035 // Explicitly declared @interface's are already synthesized.
7036 if (CDecl->isImplicitInterfaceDecl())
7038 "Legacy implicit interface rewriting not supported in moder abi");
7040 WriteModernMetadataDeclarations(Context, Result);
7041 SmallVector<ObjCIvarDecl *, 8> IVars;
7043 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7044 IVD; IVD = IVD->getNextIvar()) {
7045 // Ignore unnamed bit-fields.
7046 if (!IVD->getDeclName())
7048 IVars.push_back(IVD);
7051 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7052 "_OBJC_$_INSTANCE_VARIABLES_",
7055 // Build _objc_method_list for class's instance methods if needed
7056 SmallVector<ObjCMethodDecl *, 32>
7057 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7059 // If any of our property implementations have associated getters or
7060 // setters, produce metadata for them as well.
7061 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7062 PropEnd = IDecl->propimpl_end();
7063 Prop != PropEnd; ++Prop) {
7064 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7066 if (!Prop->getPropertyIvarDecl())
7068 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7071 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7072 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7073 InstanceMethods.push_back(Getter);
7074 if (PD->isReadOnly())
7076 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7077 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7078 InstanceMethods.push_back(Setter);
7081 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7082 "_OBJC_$_INSTANCE_METHODS_",
7083 IDecl->getNameAsString(), true);
7085 SmallVector<ObjCMethodDecl *, 32>
7086 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7088 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7089 "_OBJC_$_CLASS_METHODS_",
7090 IDecl->getNameAsString(), true);
7092 // Protocols referenced in class declaration?
7093 // Protocol's super protocol list
7094 std::vector<ObjCProtocolDecl *> RefedProtocols;
7095 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7096 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7097 E = Protocols.end();
7099 RefedProtocols.push_back(*I);
7100 // Must write out all protocol definitions in current qualifier list,
7101 // and in their nested qualifiers before writing out current definition.
7102 RewriteObjCProtocolMetaData(*I, Result);
7105 Write_protocol_list_initializer(Context, Result,
7107 "_OBJC_CLASS_PROTOCOLS_$_",
7108 IDecl->getNameAsString());
7110 // Protocol's property metadata.
7111 std::vector<ObjCPropertyDecl *> ClassProperties;
7112 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7113 E = CDecl->prop_end(); I != E; ++I)
7114 ClassProperties.push_back(*I);
7116 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7117 /* Container */IDecl,
7118 "_OBJC_$_PROP_LIST_",
7119 CDecl->getNameAsString());
7122 // Data for initializing _class_ro_t metaclass meta-data
7123 uint32_t flags = CLS_META;
7124 std::string InstanceSize;
7125 std::string InstanceStart;
7128 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7130 flags |= OBJC2_CLS_HIDDEN;
7132 if (!CDecl->getSuperClass())
7135 InstanceSize = "sizeof(struct _class_t)";
7136 InstanceStart = InstanceSize;
7137 Write__class_ro_t_initializer(Context, Result, flags,
7138 InstanceStart, InstanceSize,
7143 "_OBJC_METACLASS_RO_$_",
7144 CDecl->getNameAsString());
7147 // Data for initializing _class_ro_t meta-data
7150 flags |= OBJC2_CLS_HIDDEN;
7152 if (hasObjCExceptionAttribute(*Context, CDecl))
7153 flags |= CLS_EXCEPTION;
7155 if (!CDecl->getSuperClass())
7159 InstanceSize.clear();
7160 InstanceStart.clear();
7161 if (!ObjCSynthesizedStructs.count(CDecl)) {
7163 InstanceStart = "0";
7166 InstanceSize = "sizeof(struct ";
7167 InstanceSize += CDecl->getNameAsString();
7168 InstanceSize += "_IMPL)";
7170 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7172 RewriteIvarOffsetComputation(IVD, InstanceStart);
7175 InstanceStart = InstanceSize;
7177 Write__class_ro_t_initializer(Context, Result, flags,
7178 InstanceStart, InstanceSize,
7183 "_OBJC_CLASS_RO_$_",
7184 CDecl->getNameAsString());
7186 Write_class_t(Context, Result,
7187 "OBJC_METACLASS_$_",
7188 CDecl, /*metaclass*/true);
7190 Write_class_t(Context, Result,
7192 CDecl, /*metaclass*/false);
7194 if (ImplementationIsNonLazy(IDecl))
7195 DefinedNonLazyClasses.push_back(CDecl);
7199 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7200 int ClsDefCount = ClassImplementation.size();
7203 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7204 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7205 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7206 for (int i = 0; i < ClsDefCount; i++) {
7207 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7208 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7209 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7210 Result += CDecl->getName(); Result += ",\n";
7215 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7216 int ClsDefCount = ClassImplementation.size();
7217 int CatDefCount = CategoryImplementation.size();
7219 // For each implemented class, write out all its meta data.
7220 for (int i = 0; i < ClsDefCount; i++)
7221 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7223 RewriteClassSetupInitHook(Result);
7225 // For each implemented category, write out all its meta data.
7226 for (int i = 0; i < CatDefCount; i++)
7227 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7229 RewriteCategorySetupInitHook(Result);
7231 if (ClsDefCount > 0) {
7232 if (LangOpts.MicrosoftExt)
7233 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7234 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7235 Result += llvm::utostr(ClsDefCount); Result += "]";
7237 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7238 "regular,no_dead_strip\")))= {\n";
7239 for (int i = 0; i < ClsDefCount; i++) {
7240 Result += "\t&OBJC_CLASS_$_";
7241 Result += ClassImplementation[i]->getNameAsString();
7246 if (!DefinedNonLazyClasses.empty()) {
7247 if (LangOpts.MicrosoftExt)
7248 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7249 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7250 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7251 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7258 if (CatDefCount > 0) {
7259 if (LangOpts.MicrosoftExt)
7260 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7261 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7262 Result += llvm::utostr(CatDefCount); Result += "]";
7264 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7265 "regular,no_dead_strip\")))= {\n";
7266 for (int i = 0; i < CatDefCount; i++) {
7267 Result += "\t&_OBJC_$_CATEGORY_";
7269 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7271 Result += CategoryImplementation[i]->getNameAsString();
7277 if (!DefinedNonLazyCategories.empty()) {
7278 if (LangOpts.MicrosoftExt)
7279 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7280 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7281 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7282 Result += "\t&_OBJC_$_CATEGORY_";
7284 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7286 Result += DefinedNonLazyCategories[i]->getNameAsString();
7293 void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7294 if (LangOpts.MicrosoftExt)
7295 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7297 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7298 // version 0, ObjCABI is 2
7299 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7302 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7304 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7305 std::string &Result) {
7306 WriteModernMetadataDeclarations(Context, Result);
7307 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7308 // Find category declaration for this implementation.
7309 ObjCCategoryDecl *CDecl=0;
7310 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7311 CDecl = CDecl->getNextClassCategory())
7312 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7315 std::string FullCategoryName = ClassDecl->getNameAsString();
7316 FullCategoryName += "_$_";
7317 FullCategoryName += CDecl->getNameAsString();
7319 // Build _objc_method_list for class's instance methods if needed
7320 SmallVector<ObjCMethodDecl *, 32>
7321 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7323 // If any of our property implementations have associated getters or
7324 // setters, produce metadata for them as well.
7325 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7326 PropEnd = IDecl->propimpl_end();
7327 Prop != PropEnd; ++Prop) {
7328 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7330 if (!Prop->getPropertyIvarDecl())
7332 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7335 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7336 InstanceMethods.push_back(Getter);
7337 if (PD->isReadOnly())
7339 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7340 InstanceMethods.push_back(Setter);
7343 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7344 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7345 FullCategoryName, true);
7347 SmallVector<ObjCMethodDecl *, 32>
7348 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7350 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7351 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7352 FullCategoryName, true);
7354 // Protocols referenced in class declaration?
7355 // Protocol's super protocol list
7356 std::vector<ObjCProtocolDecl *> RefedProtocols;
7357 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7358 E = CDecl->protocol_end();
7361 RefedProtocols.push_back(*I);
7362 // Must write out all protocol definitions in current qualifier list,
7363 // and in their nested qualifiers before writing out current definition.
7364 RewriteObjCProtocolMetaData(*I, Result);
7367 Write_protocol_list_initializer(Context, Result,
7369 "_OBJC_CATEGORY_PROTOCOLS_$_",
7372 // Protocol's property metadata.
7373 std::vector<ObjCPropertyDecl *> ClassProperties;
7374 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7375 E = CDecl->prop_end(); I != E; ++I)
7376 ClassProperties.push_back(*I);
7378 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7379 /* Container */IDecl,
7380 "_OBJC_$_PROP_LIST_",
7383 Write_category_t(*this, Context, Result,
7391 // Determine if this category is also "non-lazy".
7392 if (ImplementationIsNonLazy(IDecl))
7393 DefinedNonLazyCategories.push_back(CDecl);
7397 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7398 int CatDefCount = CategoryImplementation.size();
7401 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7402 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7403 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7404 for (int i = 0; i < CatDefCount; i++) {
7405 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7406 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7407 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7408 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7409 Result += ClassDecl->getName();
7411 Result += CatDecl->getName();
7417 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7419 template<typename MethodIterator>
7420 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7421 MethodIterator MethodEnd,
7422 bool IsInstanceMethod,
7424 StringRef ClassName,
7425 std::string &Result) {
7426 if (MethodBegin == MethodEnd) return;
7428 if (!objc_impl_method) {
7429 /* struct _objc_method {
7435 Result += "\nstruct _objc_method {\n";
7436 Result += "\tSEL _cmd;\n";
7437 Result += "\tchar *method_types;\n";
7438 Result += "\tvoid *_imp;\n";
7441 objc_impl_method = true;
7444 // Build _objc_method_list for class's methods if needed
7447 struct _objc_method_list *next_method;
7449 struct _objc_method method_list[];
7452 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7454 if (LangOpts.MicrosoftExt) {
7455 if (IsInstanceMethod)
7456 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7458 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7460 Result += "static struct {\n";
7461 Result += "\tstruct _objc_method_list *next_method;\n";
7462 Result += "\tint method_count;\n";
7463 Result += "\tstruct _objc_method method_list[";
7464 Result += utostr(NumMethods);
7465 Result += "];\n} _OBJC_";
7467 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7468 Result += "_METHODS_";
7469 Result += ClassName;
7470 Result += " __attribute__ ((used, section (\"__OBJC, __";
7471 Result += IsInstanceMethod ? "inst" : "cls";
7472 Result += "_meth\")))= ";
7473 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7475 Result += "\t,{{(SEL)\"";
7476 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7477 std::string MethodTypeString;
7478 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7480 Result += MethodTypeString;
7481 Result += "\", (void *)";
7482 Result += MethodInternalNames[*MethodBegin];
7484 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7485 Result += "\t ,{(SEL)\"";
7486 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7487 std::string MethodTypeString;
7488 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7490 Result += MethodTypeString;
7491 Result += "\", (void *)";
7492 Result += MethodInternalNames[*MethodBegin];
7495 Result += "\t }\n};\n";
7498 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7499 SourceRange OldRange = IV->getSourceRange();
7500 Expr *BaseExpr = IV->getBase();
7502 // Rewrite the base, but without actually doing replaces.
7504 DisableReplaceStmtScope S(*this);
7505 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7506 IV->setBase(BaseExpr);
7509 ObjCIvarDecl *D = IV->getDecl();
7511 Expr *Replacement = IV;
7513 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7514 const ObjCInterfaceType *iFaceDecl =
7515 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7516 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7517 // lookup which class implements the instance variable.
7518 ObjCInterfaceDecl *clsDeclared = 0;
7519 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7521 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7523 // Build name of symbol holding ivar offset.
7524 std::string IvarOffsetName;
7525 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7527 ReferencedIvars[clsDeclared].insert(D);
7529 // cast offset to "char *".
7530 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7531 Context->getPointerType(Context->CharTy),
7534 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7535 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7536 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
7537 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7538 Context->UnsignedLongTy, VK_LValue,
7540 BinaryOperator *addExpr =
7541 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7542 Context->getPointerType(Context->CharTy),
7543 VK_RValue, OK_Ordinary, SourceLocation(), false);
7544 // Don't forget the parens to enforce the proper binding.
7545 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7548 QualType IvarT = D->getType();
7550 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
7551 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
7552 RD = RD->getDefinition();
7553 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7554 // decltype(((Foo_IMPL*)0)->bar) *
7555 ObjCContainerDecl *CDecl =
7556 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7557 // ivar in class extensions requires special treatment.
7558 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7559 CDecl = CatDecl->getClassInterface();
7560 std::string RecName = CDecl->getName();
7562 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7563 SourceLocation(), SourceLocation(),
7564 &Context->Idents.get(RecName.c_str()));
7565 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7566 unsigned UnsignedIntSize =
7567 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7568 Expr *Zero = IntegerLiteral::Create(*Context,
7569 llvm::APInt(UnsignedIntSize, 0),
7570 Context->UnsignedIntTy, SourceLocation());
7571 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7572 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7574 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7576 &Context->Idents.get(D->getNameAsString()),
7578 /*BitWidth=*/0, /*Mutable=*/true,
7580 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7581 FD->getType(), VK_LValue,
7583 IvarT = Context->getDecltypeType(ME, ME->getType());
7586 convertObjCTypeToCStyleType(IvarT);
7587 QualType castT = Context->getPointerType(IvarT);
7589 castExpr = NoTypeInfoCStyleCastExpr(Context,
7595 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
7596 VK_LValue, OK_Ordinary,
7598 PE = new (Context) ParenExpr(OldRange.getBegin(),
7605 ReplaceStmtWithRange(IV, Replacement, OldRange);