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