1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This coordinates the per-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenModule.h" 15 #include "CGDebugInfo.h" 16 #include "CodeGenFunction.h" 17 #include "CGCall.h" 18 #include "CGObjCRuntime.h" 19 #include "Mangle.h" 20 #include "clang/CodeGen/CodeGenOptions.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclCXX.h" 24 #include "clang/Basic/Builtins.h" 25 #include "clang/Basic/Diagnostic.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Basic/ConvertUTF.h" 29 #include "llvm/CallingConv.h" 30 #include "llvm/Module.h" 31 #include "llvm/Intrinsics.h" 32 #include "llvm/Target/TargetData.h" 33 #include "llvm/Support/ErrorHandling.h" 34 using namespace clang; 35 using namespace CodeGen; 36 37 38 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 39 llvm::Module &M, const llvm::TargetData &TD, 40 Diagnostic &diags) 41 : BlockModule(C, M, TD, Types, *this), Context(C), 42 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 43 TheTargetData(TD), Diags(diags), Types(C, M, TD), MangleCtx(C), 44 VtableInfo(*this), Runtime(0), 45 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0), 46 VMContext(M.getContext()) { 47 48 if (!Features.ObjC1) 49 Runtime = 0; 50 else if (!Features.NeXTRuntime) 51 Runtime = CreateGNUObjCRuntime(*this); 52 else if (Features.ObjCNonFragileABI) 53 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 54 else 55 Runtime = CreateMacObjCRuntime(*this); 56 57 // If debug info generation is enabled, create the CGDebugInfo object. 58 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(this) : 0; 59 } 60 61 CodeGenModule::~CodeGenModule() { 62 delete Runtime; 63 delete DebugInfo; 64 } 65 66 void CodeGenModule::Release() { 67 // We need to call this first because it can add deferred declarations. 68 EmitCXXGlobalInitFunc(); 69 70 EmitDeferred(); 71 if (Runtime) 72 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 73 AddGlobalCtor(ObjCInitFunction); 74 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 75 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 76 EmitAnnotations(); 77 EmitLLVMUsed(); 78 } 79 80 /// ErrorUnsupported - Print out an error that codegen doesn't support the 81 /// specified stmt yet. 82 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 83 bool OmitOnError) { 84 if (OmitOnError && getDiags().hasErrorOccurred()) 85 return; 86 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 87 "cannot compile this %0 yet"); 88 std::string Msg = Type; 89 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 90 << Msg << S->getSourceRange(); 91 } 92 93 /// ErrorUnsupported - Print out an error that codegen doesn't support the 94 /// specified decl yet. 95 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 96 bool OmitOnError) { 97 if (OmitOnError && getDiags().hasErrorOccurred()) 98 return; 99 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 100 "cannot compile this %0 yet"); 101 std::string Msg = Type; 102 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 103 } 104 105 LangOptions::VisibilityMode 106 CodeGenModule::getDeclVisibilityMode(const Decl *D) const { 107 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 108 if (VD->getStorageClass() == VarDecl::PrivateExtern) 109 return LangOptions::Hidden; 110 111 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 112 switch (attr->getVisibility()) { 113 default: assert(0 && "Unknown visibility!"); 114 case VisibilityAttr::DefaultVisibility: 115 return LangOptions::Default; 116 case VisibilityAttr::HiddenVisibility: 117 return LangOptions::Hidden; 118 case VisibilityAttr::ProtectedVisibility: 119 return LangOptions::Protected; 120 } 121 } 122 123 return getLangOptions().getVisibilityMode(); 124 } 125 126 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 127 const Decl *D) const { 128 // Internal definitions always have default visibility. 129 if (GV->hasLocalLinkage()) { 130 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 131 return; 132 } 133 134 switch (getDeclVisibilityMode(D)) { 135 default: assert(0 && "Unknown visibility!"); 136 case LangOptions::Default: 137 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 138 case LangOptions::Hidden: 139 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 140 case LangOptions::Protected: 141 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 142 } 143 } 144 145 const char *CodeGenModule::getMangledName(const GlobalDecl &GD) { 146 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 147 148 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 149 return getMangledCXXCtorName(D, GD.getCtorType()); 150 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 151 return getMangledCXXDtorName(D, GD.getDtorType()); 152 153 return getMangledName(ND); 154 } 155 156 /// \brief Retrieves the mangled name for the given declaration. 157 /// 158 /// If the given declaration requires a mangled name, returns an 159 /// const char* containing the mangled name. Otherwise, returns 160 /// the unmangled name. 161 /// 162 const char *CodeGenModule::getMangledName(const NamedDecl *ND) { 163 // In C, functions with no attributes never need to be mangled. Fastpath them. 164 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) { 165 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 166 return ND->getNameAsCString(); 167 } 168 169 llvm::SmallString<256> Name; 170 if (!getMangleContext().mangleName(ND, Name)) { 171 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 172 return ND->getNameAsCString(); 173 } 174 175 Name += '\0'; 176 return UniqueMangledName(Name.begin(), Name.end()); 177 } 178 179 const char *CodeGenModule::UniqueMangledName(const char *NameStart, 180 const char *NameEnd) { 181 assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!"); 182 183 return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData(); 184 } 185 186 /// AddGlobalCtor - Add a function to the list that will be called before 187 /// main() runs. 188 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 189 // FIXME: Type coercion of void()* types. 190 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 191 } 192 193 /// AddGlobalDtor - Add a function to the list that will be called 194 /// when the module is unloaded. 195 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 196 // FIXME: Type coercion of void()* types. 197 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 198 } 199 200 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 201 // Ctor function type is void()*. 202 llvm::FunctionType* CtorFTy = 203 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 204 std::vector<const llvm::Type*>(), 205 false); 206 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 207 208 // Get the type of a ctor entry, { i32, void ()* }. 209 llvm::StructType* CtorStructTy = 210 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 211 llvm::PointerType::getUnqual(CtorFTy), NULL); 212 213 // Construct the constructor and destructor arrays. 214 std::vector<llvm::Constant*> Ctors; 215 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 216 std::vector<llvm::Constant*> S; 217 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 218 I->second, false)); 219 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 220 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 221 } 222 223 if (!Ctors.empty()) { 224 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 225 new llvm::GlobalVariable(TheModule, AT, false, 226 llvm::GlobalValue::AppendingLinkage, 227 llvm::ConstantArray::get(AT, Ctors), 228 GlobalName); 229 } 230 } 231 232 void CodeGenModule::EmitAnnotations() { 233 if (Annotations.empty()) 234 return; 235 236 // Create a new global variable for the ConstantStruct in the Module. 237 llvm::Constant *Array = 238 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 239 Annotations.size()), 240 Annotations); 241 llvm::GlobalValue *gv = 242 new llvm::GlobalVariable(TheModule, Array->getType(), false, 243 llvm::GlobalValue::AppendingLinkage, Array, 244 "llvm.global.annotations"); 245 gv->setSection("llvm.metadata"); 246 } 247 248 static CodeGenModule::GVALinkage 249 GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, 250 const LangOptions &Features) { 251 // Everything located semantically within an anonymous namespace is 252 // always internal. 253 if (FD->isInAnonymousNamespace()) 254 return CodeGenModule::GVA_Internal; 255 256 // "static" functions get internal linkage. 257 if (FD->getStorageClass() == FunctionDecl::Static && !isa<CXXMethodDecl>(FD)) 258 return CodeGenModule::GVA_Internal; 259 260 // The kind of external linkage this function will have, if it is not 261 // inline or static. 262 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal; 263 if (Context.getLangOptions().CPlusPlus && 264 FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 265 External = CodeGenModule::GVA_TemplateInstantiation; 266 267 if (!FD->isInlined()) 268 return External; 269 270 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 271 // GNU or C99 inline semantics. Determine whether this symbol should be 272 // externally visible. 273 if (FD->isInlineDefinitionExternallyVisible()) 274 return External; 275 276 // C99 inline semantics, where the symbol is not externally visible. 277 return CodeGenModule::GVA_C99Inline; 278 } 279 280 // C++0x [temp.explicit]p9: 281 // [ Note: The intent is that an inline function that is the subject of 282 // an explicit instantiation declaration will still be implicitly 283 // instantiated when used so that the body can be considered for 284 // inlining, but that no out-of-line copy of the inline function would be 285 // generated in the translation unit. -- end note ] 286 if (FD->getTemplateSpecializationKind() 287 == TSK_ExplicitInstantiationDeclaration) 288 return CodeGenModule::GVA_C99Inline; 289 290 return CodeGenModule::GVA_CXXInline; 291 } 292 293 /// SetFunctionDefinitionAttributes - Set attributes for a global. 294 /// 295 /// FIXME: This is currently only done for aliases and functions, but not for 296 /// variables (these details are set in EmitGlobalVarDefinition for variables). 297 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 298 llvm::GlobalValue *GV) { 299 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features); 300 301 if (Linkage == GVA_Internal) { 302 GV->setLinkage(llvm::Function::InternalLinkage); 303 } else if (D->hasAttr<DLLExportAttr>()) { 304 GV->setLinkage(llvm::Function::DLLExportLinkage); 305 } else if (D->hasAttr<WeakAttr>()) { 306 GV->setLinkage(llvm::Function::WeakAnyLinkage); 307 } else if (Linkage == GVA_C99Inline) { 308 // In C99 mode, 'inline' functions are guaranteed to have a strong 309 // definition somewhere else, so we can use available_externally linkage. 310 GV->setLinkage(llvm::Function::AvailableExternallyLinkage); 311 } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) { 312 // In C++, the compiler has to emit a definition in every translation unit 313 // that references the function. We should use linkonce_odr because 314 // a) if all references in this translation unit are optimized away, we 315 // don't need to codegen it. b) if the function persists, it needs to be 316 // merged with other definitions. c) C++ has the ODR, so we know the 317 // definition is dependable. 318 GV->setLinkage(llvm::Function::LinkOnceODRLinkage); 319 } else { 320 assert(Linkage == GVA_StrongExternal); 321 // Otherwise, we have strong external linkage. 322 GV->setLinkage(llvm::Function::ExternalLinkage); 323 } 324 325 SetCommonAttributes(D, GV); 326 } 327 328 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 329 const CGFunctionInfo &Info, 330 llvm::Function *F) { 331 unsigned CallingConv; 332 AttributeListType AttributeList; 333 ConstructAttributeList(Info, D, AttributeList, CallingConv); 334 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 335 AttributeList.size())); 336 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 337 } 338 339 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 340 llvm::Function *F) { 341 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 342 F->addFnAttr(llvm::Attribute::NoUnwind); 343 344 if (D->hasAttr<AlwaysInlineAttr>()) 345 F->addFnAttr(llvm::Attribute::AlwaysInline); 346 347 if (D->hasAttr<NoInlineAttr>()) 348 F->addFnAttr(llvm::Attribute::NoInline); 349 350 if (Features.getStackProtectorMode() == LangOptions::SSPOn) 351 F->addFnAttr(llvm::Attribute::StackProtect); 352 else if (Features.getStackProtectorMode() == LangOptions::SSPReq) 353 F->addFnAttr(llvm::Attribute::StackProtectReq); 354 355 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) { 356 unsigned width = Context.Target.getCharWidth(); 357 F->setAlignment(AA->getAlignment() / width); 358 while ((AA = AA->getNext<AlignedAttr>())) 359 F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width)); 360 } 361 // C++ ABI requires 2-byte alignment for member functions. 362 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 363 F->setAlignment(2); 364 } 365 366 void CodeGenModule::SetCommonAttributes(const Decl *D, 367 llvm::GlobalValue *GV) { 368 setGlobalVisibility(GV, D); 369 370 if (D->hasAttr<UsedAttr>()) 371 AddUsedGlobal(GV); 372 373 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 374 GV->setSection(SA->getName()); 375 } 376 377 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 378 llvm::Function *F, 379 const CGFunctionInfo &FI) { 380 SetLLVMFunctionAttributes(D, FI, F); 381 SetLLVMFunctionAttributesForDefinition(D, F); 382 383 F->setLinkage(llvm::Function::InternalLinkage); 384 385 SetCommonAttributes(D, F); 386 } 387 388 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 389 llvm::Function *F, 390 bool IsIncompleteFunction) { 391 if (!IsIncompleteFunction) 392 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F); 393 394 // Only a few attributes are set on declarations; these may later be 395 // overridden by a definition. 396 397 if (FD->hasAttr<DLLImportAttr>()) { 398 F->setLinkage(llvm::Function::DLLImportLinkage); 399 } else if (FD->hasAttr<WeakAttr>() || 400 FD->hasAttr<WeakImportAttr>()) { 401 // "extern_weak" is overloaded in LLVM; we probably should have 402 // separate linkage types for this. 403 F->setLinkage(llvm::Function::ExternalWeakLinkage); 404 } else { 405 F->setLinkage(llvm::Function::ExternalLinkage); 406 } 407 408 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 409 F->setSection(SA->getName()); 410 } 411 412 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 413 assert(!GV->isDeclaration() && 414 "Only globals with definition can force usage."); 415 LLVMUsed.push_back(GV); 416 } 417 418 void CodeGenModule::EmitLLVMUsed() { 419 // Don't create llvm.used if there is no need. 420 if (LLVMUsed.empty()) 421 return; 422 423 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 424 425 // Convert LLVMUsed to what ConstantArray needs. 426 std::vector<llvm::Constant*> UsedArray; 427 UsedArray.resize(LLVMUsed.size()); 428 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 429 UsedArray[i] = 430 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 431 i8PTy); 432 } 433 434 if (UsedArray.empty()) 435 return; 436 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 437 438 llvm::GlobalVariable *GV = 439 new llvm::GlobalVariable(getModule(), ATy, false, 440 llvm::GlobalValue::AppendingLinkage, 441 llvm::ConstantArray::get(ATy, UsedArray), 442 "llvm.used"); 443 444 GV->setSection("llvm.metadata"); 445 } 446 447 void CodeGenModule::EmitDeferred() { 448 // Emit code for any potentially referenced deferred decls. Since a 449 // previously unused static decl may become used during the generation of code 450 // for a static function, iterate until no changes are made. 451 while (!DeferredDeclsToEmit.empty()) { 452 GlobalDecl D = DeferredDeclsToEmit.back(); 453 DeferredDeclsToEmit.pop_back(); 454 455 // The mangled name for the decl must have been emitted in GlobalDeclMap. 456 // Look it up to see if it was defined with a stronger definition (e.g. an 457 // extern inline function with a strong function redefinition). If so, 458 // just ignore the deferred decl. 459 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)]; 460 assert(CGRef && "Deferred decl wasn't referenced?"); 461 462 if (!CGRef->isDeclaration()) 463 continue; 464 465 // Otherwise, emit the definition and move on to the next one. 466 EmitGlobalDefinition(D); 467 } 468 } 469 470 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 471 /// annotation information for a given GlobalValue. The annotation struct is 472 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 473 /// GlobalValue being annotated. The second field is the constant string 474 /// created from the AnnotateAttr's annotation. The third field is a constant 475 /// string containing the name of the translation unit. The fourth field is 476 /// the line number in the file of the annotated value declaration. 477 /// 478 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 479 /// appears to. 480 /// 481 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 482 const AnnotateAttr *AA, 483 unsigned LineNo) { 484 llvm::Module *M = &getModule(); 485 486 // get [N x i8] constants for the annotation string, and the filename string 487 // which are the 2nd and 3rd elements of the global annotation structure. 488 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext); 489 llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 490 AA->getAnnotation(), true); 491 llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 492 M->getModuleIdentifier(), 493 true); 494 495 // Get the two global values corresponding to the ConstantArrays we just 496 // created to hold the bytes of the strings. 497 llvm::GlobalValue *annoGV = 498 new llvm::GlobalVariable(*M, anno->getType(), false, 499 llvm::GlobalValue::PrivateLinkage, anno, 500 GV->getName()); 501 // translation unit name string, emitted into the llvm.metadata section. 502 llvm::GlobalValue *unitGV = 503 new llvm::GlobalVariable(*M, unit->getType(), false, 504 llvm::GlobalValue::PrivateLinkage, unit, 505 ".str"); 506 507 // Create the ConstantStruct for the global annotation. 508 llvm::Constant *Fields[4] = { 509 llvm::ConstantExpr::getBitCast(GV, SBP), 510 llvm::ConstantExpr::getBitCast(annoGV, SBP), 511 llvm::ConstantExpr::getBitCast(unitGV, SBP), 512 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 513 }; 514 return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 515 } 516 517 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 518 // Never defer when EmitAllDecls is specified or the decl has 519 // attribute used. 520 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>()) 521 return false; 522 523 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 524 // Constructors and destructors should never be deferred. 525 if (FD->hasAttr<ConstructorAttr>() || 526 FD->hasAttr<DestructorAttr>()) 527 return false; 528 529 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features); 530 531 // static, static inline, always_inline, and extern inline functions can 532 // always be deferred. Normal inline functions can be deferred in C99/C++. 533 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 534 Linkage == GVA_CXXInline) 535 return true; 536 return false; 537 } 538 539 const VarDecl *VD = cast<VarDecl>(Global); 540 assert(VD->isFileVarDecl() && "Invalid decl"); 541 542 // We never want to defer structs that have non-trivial constructors or 543 // destructors. 544 545 // FIXME: Handle references. 546 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 547 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 548 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()) 549 return false; 550 } 551 } 552 553 // Static data may be deferred, but out-of-line static data members 554 // cannot be. 555 if (VD->isInAnonymousNamespace()) 556 return true; 557 if (VD->getStorageClass() == VarDecl::Static) { 558 // Initializer has side effects? 559 if (VD->getInit() && VD->getInit()->HasSideEffects(Context)) 560 return false; 561 return !(VD->isStaticDataMember() && VD->isOutOfLine()); 562 } 563 return false; 564 } 565 566 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 567 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 568 569 // If this is an alias definition (which otherwise looks like a declaration) 570 // emit it now. 571 if (Global->hasAttr<AliasAttr>()) 572 return EmitAliasDefinition(Global); 573 574 // Ignore declarations, they will be emitted on their first use. 575 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 576 // Forward declarations are emitted lazily on first use. 577 if (!FD->isThisDeclarationADefinition()) 578 return; 579 } else { 580 const VarDecl *VD = cast<VarDecl>(Global); 581 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 582 583 // In C++, if this is marked "extern", defer code generation. 584 if (getLangOptions().CPlusPlus && !VD->getInit() && 585 (VD->getStorageClass() == VarDecl::Extern || 586 VD->isExternC())) 587 return; 588 589 // In C, if this isn't a definition, defer code generation. 590 if (!getLangOptions().CPlusPlus && !VD->getInit()) 591 return; 592 } 593 594 // Defer code generation when possible if this is a static definition, inline 595 // function etc. These we only want to emit if they are used. 596 if (MayDeferGeneration(Global)) { 597 // If the value has already been used, add it directly to the 598 // DeferredDeclsToEmit list. 599 const char *MangledName = getMangledName(GD); 600 if (GlobalDeclMap.count(MangledName)) 601 DeferredDeclsToEmit.push_back(GD); 602 else { 603 // Otherwise, remember that we saw a deferred decl with this name. The 604 // first use of the mangled name will cause it to move into 605 // DeferredDeclsToEmit. 606 DeferredDecls[MangledName] = GD; 607 } 608 return; 609 } 610 611 // Otherwise emit the definition. 612 EmitGlobalDefinition(GD); 613 } 614 615 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 616 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 617 618 PrettyStackTraceDecl CrashInfo((ValueDecl *)D, D->getLocation(), 619 Context.getSourceManager(), 620 "Generating code for declaration"); 621 622 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 623 const CXXRecordDecl *RD = MD->getParent(); 624 // We have to convert it to have a record layout. 625 Types.ConvertTagDeclType(RD); 626 const CGRecordLayout &CGLayout = Types.getCGRecordLayout(RD); 627 // A definition of a KeyFunction, generates all the class data, such 628 // as vtable, rtti and the VTT. 629 if (CGLayout.getKeyFunction() 630 && (CGLayout.getKeyFunction()->getCanonicalDecl() 631 == MD->getCanonicalDecl())) 632 getVtableInfo().GenerateClassData(RD); 633 } 634 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 635 EmitCXXConstructor(CD, GD.getCtorType()); 636 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 637 EmitCXXDestructor(DD, GD.getDtorType()); 638 else if (isa<FunctionDecl>(D)) 639 EmitGlobalFunctionDefinition(GD); 640 else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 641 EmitGlobalVarDefinition(VD); 642 else { 643 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 644 } 645 } 646 647 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 648 /// module, create and return an llvm Function with the specified type. If there 649 /// is something in the module with the specified name, return it potentially 650 /// bitcasted to the right type. 651 /// 652 /// If D is non-null, it specifies a decl that correspond to this. This is used 653 /// to set the attributes on the function when it is first created. 654 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, 655 const llvm::Type *Ty, 656 GlobalDecl D) { 657 // Lookup the entry, lazily creating it if necessary. 658 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 659 if (Entry) { 660 if (Entry->getType()->getElementType() == Ty) 661 return Entry; 662 663 // Make sure the result is of the correct type. 664 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 665 return llvm::ConstantExpr::getBitCast(Entry, PTy); 666 } 667 668 // This function doesn't have a complete type (for example, the return 669 // type is an incomplete struct). Use a fake type instead, and make 670 // sure not to try to set attributes. 671 bool IsIncompleteFunction = false; 672 if (!isa<llvm::FunctionType>(Ty)) { 673 Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 674 std::vector<const llvm::Type*>(), false); 675 IsIncompleteFunction = true; 676 } 677 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 678 llvm::Function::ExternalLinkage, 679 "", &getModule()); 680 F->setName(MangledName); 681 if (D.getDecl()) 682 SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F, 683 IsIncompleteFunction); 684 Entry = F; 685 686 // This is the first use or definition of a mangled name. If there is a 687 // deferred decl with this name, remember that we need to emit it at the end 688 // of the file. 689 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 690 DeferredDecls.find(MangledName); 691 if (DDI != DeferredDecls.end()) { 692 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 693 // list, and remove it from DeferredDecls (since we don't need it anymore). 694 DeferredDeclsToEmit.push_back(DDI->second); 695 DeferredDecls.erase(DDI); 696 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 697 // If this the first reference to a C++ inline function in a class, queue up 698 // the deferred function body for emission. These are not seen as 699 // top-level declarations. 700 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 701 DeferredDeclsToEmit.push_back(D); 702 // A called constructor which has no definition or declaration need be 703 // synthesized. 704 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 705 const CXXRecordDecl *ClassDecl = 706 cast<CXXRecordDecl>(CD->getDeclContext()); 707 if (CD->isCopyConstructor(getContext())) 708 DeferredCopyConstructorToEmit(D); 709 else if (!ClassDecl->hasUserDeclaredConstructor()) 710 DeferredDeclsToEmit.push_back(D); 711 } 712 else if (isa<CXXDestructorDecl>(FD)) 713 DeferredDestructorToEmit(D); 714 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 715 if (MD->isCopyAssignment()) 716 DeferredCopyAssignmentToEmit(D); 717 } 718 719 return F; 720 } 721 722 /// Defer definition of copy constructor(s) which need be implicitly defined. 723 void CodeGenModule::DeferredCopyConstructorToEmit(GlobalDecl CopyCtorDecl) { 724 const CXXConstructorDecl *CD = 725 cast<CXXConstructorDecl>(CopyCtorDecl.getDecl()); 726 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 727 if (ClassDecl->hasTrivialCopyConstructor() || 728 ClassDecl->hasUserDeclaredCopyConstructor()) 729 return; 730 731 // First make sure all direct base classes and virtual bases and non-static 732 // data mebers which need to have their copy constructors implicitly defined 733 // are defined. 12.8.p7 734 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 735 Base != ClassDecl->bases_end(); ++Base) { 736 CXXRecordDecl *BaseClassDecl 737 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 738 if (CXXConstructorDecl *BaseCopyCtor = 739 BaseClassDecl->getCopyConstructor(Context, 0)) 740 GetAddrOfCXXConstructor(BaseCopyCtor, Ctor_Complete); 741 } 742 743 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 744 FieldEnd = ClassDecl->field_end(); 745 Field != FieldEnd; ++Field) { 746 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 747 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 748 FieldType = Array->getElementType(); 749 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 750 if ((*Field)->isAnonymousStructOrUnion()) 751 continue; 752 CXXRecordDecl *FieldClassDecl 753 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 754 if (CXXConstructorDecl *FieldCopyCtor = 755 FieldClassDecl->getCopyConstructor(Context, 0)) 756 GetAddrOfCXXConstructor(FieldCopyCtor, Ctor_Complete); 757 } 758 } 759 DeferredDeclsToEmit.push_back(CopyCtorDecl); 760 } 761 762 /// Defer definition of copy assignments which need be implicitly defined. 763 void CodeGenModule::DeferredCopyAssignmentToEmit(GlobalDecl CopyAssignDecl) { 764 const CXXMethodDecl *CD = cast<CXXMethodDecl>(CopyAssignDecl.getDecl()); 765 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 766 767 if (ClassDecl->hasTrivialCopyAssignment() || 768 ClassDecl->hasUserDeclaredCopyAssignment()) 769 return; 770 771 // First make sure all direct base classes and virtual bases and non-static 772 // data mebers which need to have their copy assignments implicitly defined 773 // are defined. 12.8.p12 774 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 775 Base != ClassDecl->bases_end(); ++Base) { 776 CXXRecordDecl *BaseClassDecl 777 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 778 const CXXMethodDecl *MD = 0; 779 if (!BaseClassDecl->hasTrivialCopyAssignment() && 780 !BaseClassDecl->hasUserDeclaredCopyAssignment() && 781 BaseClassDecl->hasConstCopyAssignment(getContext(), MD)) 782 GetAddrOfFunction(MD, 0); 783 } 784 785 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 786 FieldEnd = ClassDecl->field_end(); 787 Field != FieldEnd; ++Field) { 788 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 789 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 790 FieldType = Array->getElementType(); 791 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 792 if ((*Field)->isAnonymousStructOrUnion()) 793 continue; 794 CXXRecordDecl *FieldClassDecl 795 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 796 const CXXMethodDecl *MD = 0; 797 if (!FieldClassDecl->hasTrivialCopyAssignment() && 798 !FieldClassDecl->hasUserDeclaredCopyAssignment() && 799 FieldClassDecl->hasConstCopyAssignment(getContext(), MD)) 800 GetAddrOfFunction(MD, 0); 801 } 802 } 803 DeferredDeclsToEmit.push_back(CopyAssignDecl); 804 } 805 806 void CodeGenModule::DeferredDestructorToEmit(GlobalDecl DtorDecl) { 807 const CXXDestructorDecl *DD = cast<CXXDestructorDecl>(DtorDecl.getDecl()); 808 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext()); 809 if (ClassDecl->hasTrivialDestructor() || 810 ClassDecl->hasUserDeclaredDestructor()) 811 return; 812 813 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 814 Base != ClassDecl->bases_end(); ++Base) { 815 CXXRecordDecl *BaseClassDecl 816 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 817 if (const CXXDestructorDecl *BaseDtor = 818 BaseClassDecl->getDestructor(Context)) 819 GetAddrOfCXXDestructor(BaseDtor, Dtor_Complete); 820 } 821 822 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 823 FieldEnd = ClassDecl->field_end(); 824 Field != FieldEnd; ++Field) { 825 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 826 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 827 FieldType = Array->getElementType(); 828 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 829 if ((*Field)->isAnonymousStructOrUnion()) 830 continue; 831 CXXRecordDecl *FieldClassDecl 832 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 833 if (const CXXDestructorDecl *FieldDtor = 834 FieldClassDecl->getDestructor(Context)) 835 GetAddrOfCXXDestructor(FieldDtor, Dtor_Complete); 836 } 837 } 838 DeferredDeclsToEmit.push_back(DtorDecl); 839 } 840 841 842 /// GetAddrOfFunction - Return the address of the given function. If Ty is 843 /// non-null, then this function will use the specified type if it has to 844 /// create it (this occurs when we see a definition of the function). 845 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 846 const llvm::Type *Ty) { 847 // If there was no specific requested type, just convert it now. 848 if (!Ty) 849 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 850 return GetOrCreateLLVMFunction(getMangledName(GD), Ty, GD); 851 } 852 853 /// CreateRuntimeFunction - Create a new runtime function with the specified 854 /// type and name. 855 llvm::Constant * 856 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 857 const char *Name) { 858 // Convert Name to be a uniqued string from the IdentifierInfo table. 859 Name = getContext().Idents.get(Name).getNameStart(); 860 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 861 } 862 863 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 864 /// create and return an llvm GlobalVariable with the specified type. If there 865 /// is something in the module with the specified name, return it potentially 866 /// bitcasted to the right type. 867 /// 868 /// If D is non-null, it specifies a decl that correspond to this. This is used 869 /// to set the attributes on the global when it is first created. 870 llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, 871 const llvm::PointerType*Ty, 872 const VarDecl *D) { 873 // Lookup the entry, lazily creating it if necessary. 874 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 875 if (Entry) { 876 if (Entry->getType() == Ty) 877 return Entry; 878 879 // Make sure the result is of the correct type. 880 return llvm::ConstantExpr::getBitCast(Entry, Ty); 881 } 882 883 // This is the first use or definition of a mangled name. If there is a 884 // deferred decl with this name, remember that we need to emit it at the end 885 // of the file. 886 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 887 DeferredDecls.find(MangledName); 888 if (DDI != DeferredDecls.end()) { 889 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 890 // list, and remove it from DeferredDecls (since we don't need it anymore). 891 DeferredDeclsToEmit.push_back(DDI->second); 892 DeferredDecls.erase(DDI); 893 } 894 895 llvm::GlobalVariable *GV = 896 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 897 llvm::GlobalValue::ExternalLinkage, 898 0, "", 0, 899 false, Ty->getAddressSpace()); 900 GV->setName(MangledName); 901 902 // Handle things which are present even on external declarations. 903 if (D) { 904 // FIXME: This code is overly simple and should be merged with other global 905 // handling. 906 GV->setConstant(D->getType().isConstant(Context)); 907 908 // FIXME: Merge with other attribute handling code. 909 if (D->getStorageClass() == VarDecl::PrivateExtern) 910 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 911 912 if (D->hasAttr<WeakAttr>() || 913 D->hasAttr<WeakImportAttr>()) 914 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 915 916 GV->setThreadLocal(D->isThreadSpecified()); 917 } 918 919 return Entry = GV; 920 } 921 922 923 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 924 /// given global variable. If Ty is non-null and if the global doesn't exist, 925 /// then it will be greated with the specified type instead of whatever the 926 /// normal requested type would be. 927 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 928 const llvm::Type *Ty) { 929 assert(D->hasGlobalStorage() && "Not a global variable"); 930 QualType ASTTy = D->getType(); 931 if (Ty == 0) 932 Ty = getTypes().ConvertTypeForMem(ASTTy); 933 934 const llvm::PointerType *PTy = 935 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 936 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D); 937 } 938 939 /// CreateRuntimeVariable - Create a new runtime global variable with the 940 /// specified type and name. 941 llvm::Constant * 942 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 943 const char *Name) { 944 // Convert Name to be a uniqued string from the IdentifierInfo table. 945 Name = getContext().Idents.get(Name).getNameStart(); 946 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 947 } 948 949 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 950 assert(!D->getInit() && "Cannot emit definite definitions here!"); 951 952 if (MayDeferGeneration(D)) { 953 // If we have not seen a reference to this variable yet, place it 954 // into the deferred declarations table to be emitted if needed 955 // later. 956 const char *MangledName = getMangledName(D); 957 if (GlobalDeclMap.count(MangledName) == 0) { 958 DeferredDecls[MangledName] = D; 959 return; 960 } 961 } 962 963 // The tentative definition is the only definition. 964 EmitGlobalVarDefinition(D); 965 } 966 967 static CodeGenModule::GVALinkage 968 GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) { 969 // Everything located semantically within an anonymous namespace is 970 // always internal. 971 if (VD->isInAnonymousNamespace()) 972 return CodeGenModule::GVA_Internal; 973 974 // Handle linkage for static data members. 975 if (VD->isStaticDataMember()) { 976 switch (VD->getTemplateSpecializationKind()) { 977 case TSK_Undeclared: 978 case TSK_ExplicitSpecialization: 979 case TSK_ExplicitInstantiationDefinition: 980 return CodeGenModule::GVA_StrongExternal; 981 982 case TSK_ExplicitInstantiationDeclaration: 983 llvm::llvm_unreachable("Variable should not be instantiated"); 984 // Fall through to treat this like any other instantiation. 985 986 case TSK_ImplicitInstantiation: 987 return CodeGenModule::GVA_TemplateInstantiation; 988 } 989 } 990 991 // Static variables get internal linkage. 992 if (VD->getStorageClass() == VarDecl::Static) 993 return CodeGenModule::GVA_Internal; 994 995 return CodeGenModule::GVA_StrongExternal; 996 } 997 998 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 999 llvm::Constant *Init = 0; 1000 QualType ASTTy = D->getType(); 1001 1002 if (D->getInit() == 0) { 1003 // This is a tentative definition; tentative definitions are 1004 // implicitly initialized with { 0 }. 1005 // 1006 // Note that tentative definitions are only emitted at the end of 1007 // a translation unit, so they should never have incomplete 1008 // type. In addition, EmitTentativeDefinition makes sure that we 1009 // never attempt to emit a tentative definition if a real one 1010 // exists. A use may still exists, however, so we still may need 1011 // to do a RAUW. 1012 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1013 Init = EmitNullConstant(D->getType()); 1014 } else { 1015 Init = EmitConstantExpr(D->getInit(), D->getType()); 1016 1017 if (!Init) { 1018 QualType T = D->getInit()->getType(); 1019 if (getLangOptions().CPlusPlus) { 1020 CXXGlobalInits.push_back(D); 1021 Init = EmitNullConstant(T); 1022 } else { 1023 ErrorUnsupported(D, "static initializer"); 1024 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1025 } 1026 } 1027 } 1028 1029 const llvm::Type* InitType = Init->getType(); 1030 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1031 1032 // Strip off a bitcast if we got one back. 1033 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1034 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1035 // all zero index gep. 1036 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1037 Entry = CE->getOperand(0); 1038 } 1039 1040 // Entry is now either a Function or GlobalVariable. 1041 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1042 1043 // We have a definition after a declaration with the wrong type. 1044 // We must make a new GlobalVariable* and update everything that used OldGV 1045 // (a declaration or tentative definition) with the new GlobalVariable* 1046 // (which will be a definition). 1047 // 1048 // This happens if there is a prototype for a global (e.g. 1049 // "extern int x[];") and then a definition of a different type (e.g. 1050 // "int x[10];"). This also happens when an initializer has a different type 1051 // from the type of the global (this happens with unions). 1052 if (GV == 0 || 1053 GV->getType()->getElementType() != InitType || 1054 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1055 1056 // Remove the old entry from GlobalDeclMap so that we'll create a new one. 1057 GlobalDeclMap.erase(getMangledName(D)); 1058 1059 // Make a new global with the correct type, this is now guaranteed to work. 1060 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1061 GV->takeName(cast<llvm::GlobalValue>(Entry)); 1062 1063 // Replace all uses of the old global with the new global 1064 llvm::Constant *NewPtrForOldDecl = 1065 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1066 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1067 1068 // Erase the old global, since it is no longer used. 1069 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1070 } 1071 1072 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1073 SourceManager &SM = Context.getSourceManager(); 1074 AddAnnotation(EmitAnnotateAttr(GV, AA, 1075 SM.getInstantiationLineNumber(D->getLocation()))); 1076 } 1077 1078 GV->setInitializer(Init); 1079 1080 // If it is safe to mark the global 'constant', do so now. 1081 GV->setConstant(false); 1082 if (D->getType().isConstant(Context)) { 1083 // FIXME: In C++, if the variable has a non-trivial ctor/dtor or any mutable 1084 // members, it cannot be declared "LLVM const". 1085 GV->setConstant(true); 1086 } 1087 1088 GV->setAlignment(getContext().getDeclAlignInBytes(D)); 1089 1090 // Set the llvm linkage type as appropriate. 1091 GVALinkage Linkage = GetLinkageForVariable(getContext(), D); 1092 if (Linkage == GVA_Internal) 1093 GV->setLinkage(llvm::Function::InternalLinkage); 1094 else if (D->hasAttr<DLLImportAttr>()) 1095 GV->setLinkage(llvm::Function::DLLImportLinkage); 1096 else if (D->hasAttr<DLLExportAttr>()) 1097 GV->setLinkage(llvm::Function::DLLExportLinkage); 1098 else if (D->hasAttr<WeakAttr>()) { 1099 if (GV->isConstant()) 1100 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1101 else 1102 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1103 } else if (Linkage == GVA_TemplateInstantiation) 1104 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1105 else if (!CodeGenOpts.NoCommon && 1106 !D->hasExternalStorage() && !D->getInit() && 1107 !D->getAttr<SectionAttr>()) { 1108 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1109 // common vars aren't constant even if declared const. 1110 GV->setConstant(false); 1111 } else 1112 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1113 1114 SetCommonAttributes(D, GV); 1115 1116 // Emit global variable debug information. 1117 if (CGDebugInfo *DI = getDebugInfo()) { 1118 DI->setLocation(D->getLocation()); 1119 DI->EmitGlobalVariable(GV, D); 1120 } 1121 } 1122 1123 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1124 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1125 /// existing call uses of the old function in the module, this adjusts them to 1126 /// call the new function directly. 1127 /// 1128 /// This is not just a cleanup: the always_inline pass requires direct calls to 1129 /// functions to be able to inline them. If there is a bitcast in the way, it 1130 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1131 /// run at -O0. 1132 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1133 llvm::Function *NewFn) { 1134 // If we're redefining a global as a function, don't transform it. 1135 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1136 if (OldFn == 0) return; 1137 1138 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1139 llvm::SmallVector<llvm::Value*, 4> ArgList; 1140 1141 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1142 UI != E; ) { 1143 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1144 unsigned OpNo = UI.getOperandNo(); 1145 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++); 1146 if (!CI || OpNo != 0) continue; 1147 1148 // If the return types don't match exactly, and if the call isn't dead, then 1149 // we can't transform this call. 1150 if (CI->getType() != NewRetTy && !CI->use_empty()) 1151 continue; 1152 1153 // If the function was passed too few arguments, don't transform. If extra 1154 // arguments were passed, we silently drop them. If any of the types 1155 // mismatch, we don't transform. 1156 unsigned ArgNo = 0; 1157 bool DontTransform = false; 1158 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1159 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1160 if (CI->getNumOperands()-1 == ArgNo || 1161 CI->getOperand(ArgNo+1)->getType() != AI->getType()) { 1162 DontTransform = true; 1163 break; 1164 } 1165 } 1166 if (DontTransform) 1167 continue; 1168 1169 // Okay, we can transform this. Create the new call instruction and copy 1170 // over the required information. 1171 ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo); 1172 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1173 ArgList.end(), "", CI); 1174 ArgList.clear(); 1175 if (!NewCall->getType()->isVoidTy()) 1176 NewCall->takeName(CI); 1177 NewCall->setAttributes(CI->getAttributes()); 1178 NewCall->setCallingConv(CI->getCallingConv()); 1179 1180 // Finally, remove the old call, replacing any uses with the new one. 1181 if (!CI->use_empty()) 1182 CI->replaceAllUsesWith(NewCall); 1183 1184 // Copy any custom metadata attached with CI. 1185 llvm::MetadataContext &TheMetadata = CI->getContext().getMetadata(); 1186 TheMetadata.copyMD(CI, NewCall); 1187 1188 CI->eraseFromParent(); 1189 } 1190 } 1191 1192 1193 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1194 const llvm::FunctionType *Ty; 1195 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1196 1197 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 1198 bool isVariadic = D->getType()->getAs<FunctionProtoType>()->isVariadic(); 1199 1200 Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic); 1201 } else { 1202 Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType())); 1203 1204 // As a special case, make sure that definitions of K&R function 1205 // "type foo()" aren't declared as varargs (which forces the backend 1206 // to do unnecessary work). 1207 if (D->getType()->isFunctionNoProtoType()) { 1208 assert(Ty->isVarArg() && "Didn't lower type as expected"); 1209 // Due to stret, the lowered function could have arguments. 1210 // Just create the same type as was lowered by ConvertType 1211 // but strip off the varargs bit. 1212 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end()); 1213 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false); 1214 } 1215 } 1216 1217 // Get or create the prototype for the function. 1218 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1219 1220 // Strip off a bitcast if we got one back. 1221 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1222 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1223 Entry = CE->getOperand(0); 1224 } 1225 1226 1227 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1228 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1229 1230 // If the types mismatch then we have to rewrite the definition. 1231 assert(OldFn->isDeclaration() && 1232 "Shouldn't replace non-declaration"); 1233 1234 // F is the Function* for the one with the wrong type, we must make a new 1235 // Function* and update everything that used F (a declaration) with the new 1236 // Function* (which will be a definition). 1237 // 1238 // This happens if there is a prototype for a function 1239 // (e.g. "int f()") and then a definition of a different type 1240 // (e.g. "int f(int x)"). Start by making a new function of the 1241 // correct type, RAUW, then steal the name. 1242 GlobalDeclMap.erase(getMangledName(D)); 1243 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1244 NewFn->takeName(OldFn); 1245 1246 // If this is an implementation of a function without a prototype, try to 1247 // replace any existing uses of the function (which may be calls) with uses 1248 // of the new function 1249 if (D->getType()->isFunctionNoProtoType()) { 1250 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1251 OldFn->removeDeadConstantUsers(); 1252 } 1253 1254 // Replace uses of F with the Function we will endow with a body. 1255 if (!Entry->use_empty()) { 1256 llvm::Constant *NewPtrForOldDecl = 1257 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1258 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1259 } 1260 1261 // Ok, delete the old function now, which is dead. 1262 OldFn->eraseFromParent(); 1263 1264 Entry = NewFn; 1265 } 1266 1267 llvm::Function *Fn = cast<llvm::Function>(Entry); 1268 1269 CodeGenFunction(*this).GenerateCode(D, Fn); 1270 1271 SetFunctionDefinitionAttributes(D, Fn); 1272 SetLLVMFunctionAttributesForDefinition(D, Fn); 1273 1274 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1275 AddGlobalCtor(Fn, CA->getPriority()); 1276 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1277 AddGlobalDtor(Fn, DA->getPriority()); 1278 } 1279 1280 void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { 1281 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1282 assert(AA && "Not an alias?"); 1283 1284 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1285 1286 // Unique the name through the identifier table. 1287 const char *AliaseeName = AA->getAliasee().c_str(); 1288 AliaseeName = getContext().Idents.get(AliaseeName).getNameStart(); 1289 1290 // Create a reference to the named value. This ensures that it is emitted 1291 // if a deferred decl. 1292 llvm::Constant *Aliasee; 1293 if (isa<llvm::FunctionType>(DeclTy)) 1294 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl()); 1295 else 1296 Aliasee = GetOrCreateLLVMGlobal(AliaseeName, 1297 llvm::PointerType::getUnqual(DeclTy), 0); 1298 1299 // Create the new alias itself, but don't set a name yet. 1300 llvm::GlobalValue *GA = 1301 new llvm::GlobalAlias(Aliasee->getType(), 1302 llvm::Function::ExternalLinkage, 1303 "", Aliasee, &getModule()); 1304 1305 // See if there is already something with the alias' name in the module. 1306 const char *MangledName = getMangledName(D); 1307 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 1308 1309 if (Entry && !Entry->isDeclaration()) { 1310 // If there is a definition in the module, then it wins over the alias. 1311 // This is dubious, but allow it to be safe. Just ignore the alias. 1312 GA->eraseFromParent(); 1313 return; 1314 } 1315 1316 if (Entry) { 1317 // If there is a declaration in the module, then we had an extern followed 1318 // by the alias, as in: 1319 // extern int test6(); 1320 // ... 1321 // int test6() __attribute__((alias("test7"))); 1322 // 1323 // Remove it and replace uses of it with the alias. 1324 1325 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1326 Entry->getType())); 1327 Entry->eraseFromParent(); 1328 } 1329 1330 // Now we know that there is no conflict, set the name. 1331 Entry = GA; 1332 GA->setName(MangledName); 1333 1334 // Set attributes which are particular to an alias; this is a 1335 // specialization of the attributes which may be set on a global 1336 // variable/function. 1337 if (D->hasAttr<DLLExportAttr>()) { 1338 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1339 // The dllexport attribute is ignored for undefined symbols. 1340 if (FD->getBody()) 1341 GA->setLinkage(llvm::Function::DLLExportLinkage); 1342 } else { 1343 GA->setLinkage(llvm::Function::DLLExportLinkage); 1344 } 1345 } else if (D->hasAttr<WeakAttr>() || 1346 D->hasAttr<WeakImportAttr>()) { 1347 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1348 } 1349 1350 SetCommonAttributes(D, GA); 1351 } 1352 1353 /// getBuiltinLibFunction - Given a builtin id for a function like 1354 /// "__builtin_fabsf", return a Function* for "fabsf". 1355 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1356 unsigned BuiltinID) { 1357 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1358 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1359 "isn't a lib fn"); 1360 1361 // Get the name, skip over the __builtin_ prefix (if necessary). 1362 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1363 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1364 Name += 10; 1365 1366 // Get the type for the builtin. 1367 ASTContext::GetBuiltinTypeError Error; 1368 QualType Type = Context.GetBuiltinType(BuiltinID, Error); 1369 assert(Error == ASTContext::GE_None && "Can't get builtin type"); 1370 1371 const llvm::FunctionType *Ty = 1372 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 1373 1374 // Unique the name through the identifier table. 1375 Name = getContext().Idents.get(Name).getNameStart(); 1376 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1377 } 1378 1379 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1380 unsigned NumTys) { 1381 return llvm::Intrinsic::getDeclaration(&getModule(), 1382 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1383 } 1384 1385 llvm::Function *CodeGenModule::getMemCpyFn() { 1386 if (MemCpyFn) return MemCpyFn; 1387 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1388 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 1389 } 1390 1391 llvm::Function *CodeGenModule::getMemMoveFn() { 1392 if (MemMoveFn) return MemMoveFn; 1393 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1394 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 1395 } 1396 1397 llvm::Function *CodeGenModule::getMemSetFn() { 1398 if (MemSetFn) return MemSetFn; 1399 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1400 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 1401 } 1402 1403 static llvm::StringMapEntry<llvm::Constant*> & 1404 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1405 const StringLiteral *Literal, 1406 bool TargetIsLSB, 1407 bool &IsUTF16, 1408 unsigned &StringLength) { 1409 unsigned NumBytes = Literal->getByteLength(); 1410 1411 // Check for simple case. 1412 if (!Literal->containsNonAsciiOrNull()) { 1413 StringLength = NumBytes; 1414 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1415 StringLength)); 1416 } 1417 1418 // Otherwise, convert the UTF8 literals into a byte string. 1419 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1420 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); 1421 UTF16 *ToPtr = &ToBuf[0]; 1422 1423 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1424 &ToPtr, ToPtr + NumBytes, 1425 strictConversion); 1426 1427 // Check for conversion failure. 1428 if (Result != conversionOK) { 1429 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1430 // this duplicate code. 1431 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1432 StringLength = NumBytes; 1433 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1434 StringLength)); 1435 } 1436 1437 // ConvertUTF8toUTF16 returns the length in ToPtr. 1438 StringLength = ToPtr - &ToBuf[0]; 1439 1440 // Render the UTF-16 string into a byte array and convert to the target byte 1441 // order. 1442 // 1443 // FIXME: This isn't something we should need to do here. 1444 llvm::SmallString<128> AsBytes; 1445 AsBytes.reserve(StringLength * 2); 1446 for (unsigned i = 0; i != StringLength; ++i) { 1447 unsigned short Val = ToBuf[i]; 1448 if (TargetIsLSB) { 1449 AsBytes.push_back(Val & 0xFF); 1450 AsBytes.push_back(Val >> 8); 1451 } else { 1452 AsBytes.push_back(Val >> 8); 1453 AsBytes.push_back(Val & 0xFF); 1454 } 1455 } 1456 // Append one extra null character, the second is automatically added by our 1457 // caller. 1458 AsBytes.push_back(0); 1459 1460 IsUTF16 = true; 1461 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1462 } 1463 1464 llvm::Constant * 1465 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1466 unsigned StringLength = 0; 1467 bool isUTF16 = false; 1468 llvm::StringMapEntry<llvm::Constant*> &Entry = 1469 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1470 getTargetData().isLittleEndian(), 1471 isUTF16, StringLength); 1472 1473 if (llvm::Constant *C = Entry.getValue()) 1474 return C; 1475 1476 llvm::Constant *Zero = 1477 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1478 llvm::Constant *Zeros[] = { Zero, Zero }; 1479 1480 // If we don't already have it, get __CFConstantStringClassReference. 1481 if (!CFConstantStringClassRef) { 1482 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1483 Ty = llvm::ArrayType::get(Ty, 0); 1484 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1485 "__CFConstantStringClassReference"); 1486 // Decay array -> ptr 1487 CFConstantStringClassRef = 1488 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1489 } 1490 1491 QualType CFTy = getContext().getCFConstantStringType(); 1492 1493 const llvm::StructType *STy = 1494 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1495 1496 std::vector<llvm::Constant*> Fields(4); 1497 1498 // Class pointer. 1499 Fields[0] = CFConstantStringClassRef; 1500 1501 // Flags. 1502 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1503 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1504 llvm::ConstantInt::get(Ty, 0x07C8); 1505 1506 // String pointer. 1507 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1508 1509 const char *Sect = 0; 1510 llvm::GlobalValue::LinkageTypes Linkage; 1511 bool isConstant; 1512 if (isUTF16) { 1513 Sect = getContext().Target.getUnicodeStringSection(); 1514 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1515 Linkage = llvm::GlobalValue::InternalLinkage; 1516 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1517 // does make plain ascii ones writable. 1518 isConstant = true; 1519 } else { 1520 Linkage = llvm::GlobalValue::PrivateLinkage; 1521 isConstant = !Features.WritableStrings; 1522 } 1523 1524 llvm::GlobalVariable *GV = 1525 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1526 ".str"); 1527 if (Sect) 1528 GV->setSection(Sect); 1529 if (isUTF16) { 1530 unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8; 1531 GV->setAlignment(Align); 1532 } 1533 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1534 1535 // String length. 1536 Ty = getTypes().ConvertType(getContext().LongTy); 1537 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1538 1539 // The struct. 1540 C = llvm::ConstantStruct::get(STy, Fields); 1541 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1542 llvm::GlobalVariable::PrivateLinkage, C, 1543 "_unnamed_cfstring_"); 1544 if (const char *Sect = getContext().Target.getCFStringSection()) 1545 GV->setSection(Sect); 1546 Entry.setValue(GV); 1547 1548 return GV; 1549 } 1550 1551 /// GetStringForStringLiteral - Return the appropriate bytes for a 1552 /// string literal, properly padded to match the literal type. 1553 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1554 const char *StrData = E->getStrData(); 1555 unsigned Len = E->getByteLength(); 1556 1557 const ConstantArrayType *CAT = 1558 getContext().getAsConstantArrayType(E->getType()); 1559 assert(CAT && "String isn't pointer or array!"); 1560 1561 // Resize the string to the right size. 1562 std::string Str(StrData, StrData+Len); 1563 uint64_t RealLen = CAT->getSize().getZExtValue(); 1564 1565 if (E->isWide()) 1566 RealLen *= getContext().Target.getWCharWidth()/8; 1567 1568 Str.resize(RealLen, '\0'); 1569 1570 return Str; 1571 } 1572 1573 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1574 /// constant array for the given string literal. 1575 llvm::Constant * 1576 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1577 // FIXME: This can be more efficient. 1578 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1579 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1580 if (S->isWide()) { 1581 llvm::Type *DestTy = 1582 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1583 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1584 } 1585 return C; 1586 } 1587 1588 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1589 /// array for the given ObjCEncodeExpr node. 1590 llvm::Constant * 1591 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1592 std::string Str; 1593 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1594 1595 return GetAddrOfConstantCString(Str); 1596 } 1597 1598 1599 /// GenerateWritableString -- Creates storage for a string literal. 1600 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1601 bool constant, 1602 CodeGenModule &CGM, 1603 const char *GlobalName) { 1604 // Create Constant for this string literal. Don't add a '\0'. 1605 llvm::Constant *C = 1606 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1607 1608 // Create a global variable for this string 1609 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1610 llvm::GlobalValue::PrivateLinkage, 1611 C, GlobalName); 1612 } 1613 1614 /// GetAddrOfConstantString - Returns a pointer to a character array 1615 /// containing the literal. This contents are exactly that of the 1616 /// given string, i.e. it will not be null terminated automatically; 1617 /// see GetAddrOfConstantCString. Note that whether the result is 1618 /// actually a pointer to an LLVM constant depends on 1619 /// Feature.WriteableStrings. 1620 /// 1621 /// The result has pointer to array type. 1622 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1623 const char *GlobalName) { 1624 bool IsConstant = !Features.WritableStrings; 1625 1626 // Get the default prefix if a name wasn't specified. 1627 if (!GlobalName) 1628 GlobalName = ".str"; 1629 1630 // Don't share any string literals if strings aren't constant. 1631 if (!IsConstant) 1632 return GenerateStringLiteral(str, false, *this, GlobalName); 1633 1634 llvm::StringMapEntry<llvm::Constant *> &Entry = 1635 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1636 1637 if (Entry.getValue()) 1638 return Entry.getValue(); 1639 1640 // Create a global variable for this. 1641 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1642 Entry.setValue(C); 1643 return C; 1644 } 1645 1646 /// GetAddrOfConstantCString - Returns a pointer to a character 1647 /// array containing the literal and a terminating '\-' 1648 /// character. The result has pointer to array type. 1649 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1650 const char *GlobalName){ 1651 return GetAddrOfConstantString(str + '\0', GlobalName); 1652 } 1653 1654 /// EmitObjCPropertyImplementations - Emit information for synthesized 1655 /// properties for an implementation. 1656 void CodeGenModule::EmitObjCPropertyImplementations(const 1657 ObjCImplementationDecl *D) { 1658 for (ObjCImplementationDecl::propimpl_iterator 1659 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1660 ObjCPropertyImplDecl *PID = *i; 1661 1662 // Dynamic is just for type-checking. 1663 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1664 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1665 1666 // Determine which methods need to be implemented, some may have 1667 // been overridden. Note that ::isSynthesized is not the method 1668 // we want, that just indicates if the decl came from a 1669 // property. What we want to know is if the method is defined in 1670 // this implementation. 1671 if (!D->getInstanceMethod(PD->getGetterName())) 1672 CodeGenFunction(*this).GenerateObjCGetter( 1673 const_cast<ObjCImplementationDecl *>(D), PID); 1674 if (!PD->isReadOnly() && 1675 !D->getInstanceMethod(PD->getSetterName())) 1676 CodeGenFunction(*this).GenerateObjCSetter( 1677 const_cast<ObjCImplementationDecl *>(D), PID); 1678 } 1679 } 1680 } 1681 1682 /// EmitNamespace - Emit all declarations in a namespace. 1683 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1684 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1685 I != E; ++I) 1686 EmitTopLevelDecl(*I); 1687 } 1688 1689 // EmitLinkageSpec - Emit all declarations in a linkage spec. 1690 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1691 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1692 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1693 ErrorUnsupported(LSD, "linkage spec"); 1694 return; 1695 } 1696 1697 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1698 I != E; ++I) 1699 EmitTopLevelDecl(*I); 1700 } 1701 1702 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1703 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1704 // If an error has occurred, stop code generation, but continue 1705 // parsing and semantic analysis (to ensure all warnings and errors 1706 // are emitted). 1707 if (Diags.hasErrorOccurred()) 1708 return; 1709 1710 // Ignore dependent declarations. 1711 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1712 return; 1713 1714 switch (D->getKind()) { 1715 case Decl::CXXConversion: 1716 case Decl::CXXMethod: 1717 case Decl::Function: 1718 // Skip function templates 1719 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1720 return; 1721 1722 EmitGlobal(cast<FunctionDecl>(D)); 1723 break; 1724 1725 case Decl::Var: 1726 EmitGlobal(cast<VarDecl>(D)); 1727 break; 1728 1729 // C++ Decls 1730 case Decl::Namespace: 1731 EmitNamespace(cast<NamespaceDecl>(D)); 1732 break; 1733 // No code generation needed. 1734 case Decl::UsingShadow: 1735 case Decl::Using: 1736 case Decl::UsingDirective: 1737 case Decl::ClassTemplate: 1738 case Decl::FunctionTemplate: 1739 case Decl::NamespaceAlias: 1740 break; 1741 case Decl::CXXConstructor: 1742 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1743 break; 1744 case Decl::CXXDestructor: 1745 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1746 break; 1747 1748 case Decl::StaticAssert: 1749 // Nothing to do. 1750 break; 1751 1752 // Objective-C Decls 1753 1754 // Forward declarations, no (immediate) code generation. 1755 case Decl::ObjCClass: 1756 case Decl::ObjCForwardProtocol: 1757 case Decl::ObjCCategory: 1758 case Decl::ObjCInterface: 1759 break; 1760 1761 case Decl::ObjCProtocol: 1762 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1763 break; 1764 1765 case Decl::ObjCCategoryImpl: 1766 // Categories have properties but don't support synthesize so we 1767 // can ignore them here. 1768 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1769 break; 1770 1771 case Decl::ObjCImplementation: { 1772 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1773 EmitObjCPropertyImplementations(OMD); 1774 Runtime->GenerateClass(OMD); 1775 break; 1776 } 1777 case Decl::ObjCMethod: { 1778 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1779 // If this is not a prototype, emit the body. 1780 if (OMD->getBody()) 1781 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1782 break; 1783 } 1784 case Decl::ObjCCompatibleAlias: 1785 // compatibility-alias is a directive and has no code gen. 1786 break; 1787 1788 case Decl::LinkageSpec: 1789 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 1790 break; 1791 1792 case Decl::FileScopeAsm: { 1793 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1794 std::string AsmString(AD->getAsmString()->getStrData(), 1795 AD->getAsmString()->getByteLength()); 1796 1797 const std::string &S = getModule().getModuleInlineAsm(); 1798 if (S.empty()) 1799 getModule().setModuleInlineAsm(AsmString); 1800 else 1801 getModule().setModuleInlineAsm(S + '\n' + AsmString); 1802 break; 1803 } 1804 1805 default: 1806 // Make sure we handled everything we should, every other kind is a 1807 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 1808 // function. Need to recode Decl::Kind to do that easily. 1809 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1810 } 1811 } 1812