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 "CGDebugInfo.h" 15 #include "CodeGenModule.h" 16 #include "CodeGenFunction.h" 17 #include "CGObjCRuntime.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/Basic/Diagnostic.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Basic/TargetInfo.h" 23 #include "llvm/CallingConv.h" 24 #include "llvm/Module.h" 25 #include "llvm/Intrinsics.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Analysis/Verifier.h" 28 using namespace clang; 29 using namespace CodeGen; 30 31 32 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO, 33 llvm::Module &M, const llvm::TargetData &TD, 34 Diagnostic &diags, bool GenerateDebugInfo) 35 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags), 36 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0), 37 CFConstantStringClassRef(0) { 38 39 if (Features.ObjC1) { 40 if (Features.NeXTRuntime) { 41 Runtime = CreateMacObjCRuntime(*this); 42 } else { 43 Runtime = CreateGNUObjCRuntime(*this); 44 } 45 } 46 47 // If debug info generation is enabled, create the CGDebugInfo object. 48 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0; 49 } 50 51 CodeGenModule::~CodeGenModule() { 52 delete Runtime; 53 delete DebugInfo; 54 } 55 56 void CodeGenModule::Release() { 57 EmitStatics(); 58 if (Runtime) 59 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 60 AddGlobalCtor(ObjCInitFunction); 61 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 62 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 63 EmitAnnotations(); 64 // Run the verifier to check that the generated code is consistent. 65 assert(!verifyModule(TheModule)); 66 } 67 68 /// ErrorUnsupported - Print out an error that codegen doesn't support the 69 /// specified stmt yet. 70 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 71 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 72 "cannot codegen this %0 yet"); 73 SourceRange Range = S->getSourceRange(); 74 std::string Msg = Type; 75 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID, 76 &Msg, 1, &Range, 1); 77 } 78 79 /// ErrorUnsupported - Print out an error that codegen doesn't support the 80 /// specified decl yet. 81 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 82 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 83 "cannot codegen this %0 yet"); 84 std::string Msg = Type; 85 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID, 86 &Msg, 1); 87 } 88 89 /// setGlobalVisibility - Set the visibility for the given LLVM 90 /// GlobalValue according to the given clang AST visibility value. 91 static void setGlobalVisibility(llvm::GlobalValue *GV, 92 VisibilityAttr::VisibilityTypes Vis) { 93 switch (Vis) { 94 default: assert(0 && "Unknown visibility!"); 95 case VisibilityAttr::DefaultVisibility: 96 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 97 break; 98 case VisibilityAttr::HiddenVisibility: 99 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 100 break; 101 case VisibilityAttr::ProtectedVisibility: 102 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 103 break; 104 } 105 } 106 107 /// AddGlobalCtor - Add a function to the list that will be called before 108 /// main() runs. 109 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 110 // TODO: Type coercion of void()* types. 111 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 112 } 113 114 /// AddGlobalDtor - Add a function to the list that will be called 115 /// when the module is unloaded. 116 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 117 // TODO: Type coercion of void()* types. 118 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 119 } 120 121 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 122 // Ctor function type is void()*. 123 llvm::FunctionType* CtorFTy = 124 llvm::FunctionType::get(llvm::Type::VoidTy, 125 std::vector<const llvm::Type*>(), 126 false); 127 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 128 129 // Get the type of a ctor entry, { i32, void ()* }. 130 llvm::StructType* CtorStructTy = 131 llvm::StructType::get(llvm::Type::Int32Ty, 132 llvm::PointerType::getUnqual(CtorFTy), NULL); 133 134 // Construct the constructor and destructor arrays. 135 std::vector<llvm::Constant*> Ctors; 136 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 137 std::vector<llvm::Constant*> S; 138 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false)); 139 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 140 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 141 } 142 143 if (!Ctors.empty()) { 144 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 145 new llvm::GlobalVariable(AT, false, 146 llvm::GlobalValue::AppendingLinkage, 147 llvm::ConstantArray::get(AT, Ctors), 148 GlobalName, 149 &TheModule); 150 } 151 } 152 153 void CodeGenModule::EmitAnnotations() { 154 if (Annotations.empty()) 155 return; 156 157 // Create a new global variable for the ConstantStruct in the Module. 158 llvm::Constant *Array = 159 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 160 Annotations.size()), 161 Annotations); 162 llvm::GlobalValue *gv = 163 new llvm::GlobalVariable(Array->getType(), false, 164 llvm::GlobalValue::AppendingLinkage, Array, 165 "llvm.global.annotations", &TheModule); 166 gv->setSection("llvm.metadata"); 167 } 168 169 void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD, 170 llvm::GlobalValue *GV) { 171 // TODO: Set up linkage and many other things. Note, this is a simple 172 // approximation of what we really want. 173 if (FD->getStorageClass() == FunctionDecl::Static) 174 GV->setLinkage(llvm::Function::InternalLinkage); 175 else if (FD->getAttr<DLLImportAttr>()) 176 GV->setLinkage(llvm::Function::DLLImportLinkage); 177 else if (FD->getAttr<DLLExportAttr>()) 178 GV->setLinkage(llvm::Function::DLLExportLinkage); 179 else if (FD->getAttr<WeakAttr>() || FD->isInline()) 180 GV->setLinkage(llvm::Function::WeakLinkage); 181 182 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>()) 183 setGlobalVisibility(GV, attr->getVisibility()); 184 // FIXME: else handle -fvisibility 185 186 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) { 187 // Prefaced with special LLVM marker to indicate that the name 188 // should not be munged. 189 GV->setName("\01" + ALA->getLabel()); 190 } 191 } 192 193 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 194 llvm::Function *F, 195 const llvm::FunctionType *FTy) { 196 unsigned FuncAttrs = 0; 197 if (FD->getAttr<NoThrowAttr>()) 198 FuncAttrs |= llvm::ParamAttr::NoUnwind; 199 if (FD->getAttr<NoReturnAttr>()) 200 FuncAttrs |= llvm::ParamAttr::NoReturn; 201 202 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList; 203 if (FuncAttrs) 204 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs)); 205 // Note that there is parallel code in CodeGenFunction::EmitCallExpr 206 bool AggregateReturn = CodeGenFunction::hasAggregateLLVMType(FD->getResultType()); 207 if (AggregateReturn) 208 ParamAttrList.push_back( 209 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet)); 210 unsigned increment = AggregateReturn ? 2 : 1; 211 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType()); 212 if (FTP) { 213 for (unsigned i = 0; i < FTP->getNumArgs(); i++) { 214 QualType ParamType = FTP->getArgType(i); 215 unsigned ParamAttrs = 0; 216 if (ParamType->isRecordType()) 217 ParamAttrs |= llvm::ParamAttr::ByVal; 218 if (ParamType->isSignedIntegerType() && 219 ParamType->isPromotableIntegerType()) 220 ParamAttrs |= llvm::ParamAttr::SExt; 221 if (ParamType->isUnsignedIntegerType() && 222 ParamType->isPromotableIntegerType()) 223 ParamAttrs |= llvm::ParamAttr::ZExt; 224 if (ParamAttrs) 225 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment, 226 ParamAttrs)); 227 } 228 } 229 230 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(), 231 ParamAttrList.size())); 232 233 // Set the appropriate calling convention for the Function. 234 if (FD->getAttr<FastCallAttr>()) 235 F->setCallingConv(llvm::CallingConv::Fast); 236 237 SetGlobalValueAttributes(FD, F); 238 } 239 240 void CodeGenModule::EmitStatics() { 241 // Emit code for each used static decl encountered. Since a previously unused 242 // static decl may become used during the generation of code for a static 243 // function, iterate until no changes are made. 244 bool Changed; 245 do { 246 Changed = false; 247 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) { 248 const ValueDecl *D = StaticDecls[i]; 249 250 // Check if we have used a decl with the same name 251 // FIXME: The AST should have some sort of aggregate decls or 252 // global symbol map. 253 if (!GlobalDeclMap.count(D->getIdentifier())) 254 continue; 255 256 // Emit the definition. 257 EmitGlobalDefinition(D); 258 259 // Erase the used decl from the list. 260 StaticDecls[i] = StaticDecls.back(); 261 StaticDecls.pop_back(); 262 --i; 263 --e; 264 265 // Remember that we made a change. 266 Changed = true; 267 } 268 } while (Changed); 269 } 270 271 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 272 /// annotation information for a given GlobalValue. The annotation struct is 273 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 274 /// GlobalValue being annotated. The second field is the constant string 275 /// created from the AnnotateAttr's annotation. The third field is a constant 276 /// string containing the name of the translation unit. The fourth field is 277 /// the line number in the file of the annotated value declaration. 278 /// 279 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 280 /// appears to. 281 /// 282 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 283 const AnnotateAttr *AA, 284 unsigned LineNo) { 285 llvm::Module *M = &getModule(); 286 287 // get [N x i8] constants for the annotation string, and the filename string 288 // which are the 2nd and 3rd elements of the global annotation structure. 289 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 290 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true); 291 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(), 292 true); 293 294 // Get the two global values corresponding to the ConstantArrays we just 295 // created to hold the bytes of the strings. 296 llvm::GlobalValue *annoGV = 297 new llvm::GlobalVariable(anno->getType(), false, 298 llvm::GlobalValue::InternalLinkage, anno, 299 GV->getName() + ".str", M); 300 // translation unit name string, emitted into the llvm.metadata section. 301 llvm::GlobalValue *unitGV = 302 new llvm::GlobalVariable(unit->getType(), false, 303 llvm::GlobalValue::InternalLinkage, unit, ".str", M); 304 305 // Create the ConstantStruct that is the global annotion. 306 llvm::Constant *Fields[4] = { 307 llvm::ConstantExpr::getBitCast(GV, SBP), 308 llvm::ConstantExpr::getBitCast(annoGV, SBP), 309 llvm::ConstantExpr::getBitCast(unitGV, SBP), 310 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo) 311 }; 312 return llvm::ConstantStruct::get(Fields, 4, false); 313 } 314 315 void CodeGenModule::EmitGlobal(const ValueDecl *Global) { 316 bool isDef, isStatic; 317 318 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 319 isDef = (FD->isThisDeclarationADefinition() || 320 FD->getAttr<AliasAttr>()); 321 isStatic = FD->getStorageClass() == FunctionDecl::Static; 322 } else if (const VarDecl *VD = cast<VarDecl>(Global)) { 323 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 324 325 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0); 326 isStatic = VD->getStorageClass() == VarDecl::Static; 327 } else { 328 assert(0 && "Invalid argument to EmitGlobal"); 329 return; 330 } 331 332 // Forward declarations are emitted lazily on first use. 333 if (!isDef) 334 return; 335 336 // If the global is a static, defer code generation until later so 337 // we can easily omit unused statics. 338 if (isStatic) { 339 StaticDecls.push_back(Global); 340 return; 341 } 342 343 // Otherwise emit the definition. 344 EmitGlobalDefinition(Global); 345 } 346 347 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) { 348 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 349 EmitGlobalFunctionDefinition(FD); 350 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 351 EmitGlobalVarDefinition(VD); 352 } else { 353 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 354 } 355 } 356 357 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) { 358 assert(D->hasGlobalStorage() && "Not a global variable"); 359 360 QualType ASTTy = D->getType(); 361 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 362 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 363 364 // Lookup the entry, lazily creating it if necessary. 365 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()]; 366 if (!Entry) 367 Entry = new llvm::GlobalVariable(Ty, false, 368 llvm::GlobalValue::ExternalLinkage, 369 0, D->getName(), &getModule(), 0, 370 ASTTy.getAddressSpace()); 371 372 // Make sure the result is of the correct type. 373 return llvm::ConstantExpr::getBitCast(Entry, PTy); 374 } 375 376 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 377 llvm::Constant *Init = 0; 378 QualType ASTTy = D->getType(); 379 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy); 380 381 if (D->getInit() == 0) { 382 // This is a tentative definition; tentative definitions are 383 // implicitly initialized with { 0 } 384 const llvm::Type* InitTy; 385 if (ASTTy->isIncompleteArrayType()) { 386 // An incomplete array is normally [ TYPE x 0 ], but we need 387 // to fix it to [ TYPE x 1 ]. 388 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy); 389 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1); 390 } else { 391 InitTy = VarTy; 392 } 393 Init = llvm::Constant::getNullValue(InitTy); 394 } else { 395 Init = EmitConstantExpr(D->getInit()); 396 } 397 const llvm::Type* InitType = Init->getType(); 398 399 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()]; 400 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry); 401 402 if (!GV) { 403 GV = new llvm::GlobalVariable(InitType, false, 404 llvm::GlobalValue::ExternalLinkage, 405 0, D->getName(), &getModule(), 0, 406 ASTTy.getAddressSpace()); 407 } else if (GV->getType() != 408 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) { 409 // We have a definition after a prototype with the wrong type. 410 // We must make a new GlobalVariable* and update everything that used OldGV 411 // (a declaration or tentative definition) with the new GlobalVariable* 412 // (which will be a definition). 413 // 414 // This happens if there is a prototype for a global (e.g. "extern int x[];") 415 // and then a definition of a different type (e.g. "int x[10];"). This also 416 // happens when an initializer has a different type from the type of the 417 // global (this happens with unions). 418 // 419 // FIXME: This also ends up happening if there's a definition followed by 420 // a tentative definition! (Although Sema rejects that construct 421 // at the moment.) 422 423 // Save the old global 424 llvm::GlobalVariable *OldGV = GV; 425 426 // Make a new global with the correct type 427 GV = new llvm::GlobalVariable(InitType, false, 428 llvm::GlobalValue::ExternalLinkage, 429 0, D->getName(), &getModule(), 0, 430 ASTTy.getAddressSpace()); 431 // Steal the name of the old global 432 GV->takeName(OldGV); 433 434 // Replace all uses of the old global with the new global 435 llvm::Constant *NewPtrForOldDecl = 436 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 437 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 438 439 // Erase the old global, since it is no longer used. 440 OldGV->eraseFromParent(); 441 } 442 443 Entry = GV; 444 445 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 446 SourceManager &SM = Context.getSourceManager(); 447 AddAnnotation(EmitAnnotateAttr(GV, AA, 448 SM.getLogicalLineNumber(D->getLocation()))); 449 } 450 451 GV->setInitializer(Init); 452 GV->setConstant(D->getType().isConstant(Context)); 453 454 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays 455 unsigned Align; 456 if (const IncompleteArrayType* IAT = 457 Context.getAsIncompleteArrayType(D->getType())) 458 Align = Context.getTypeAlign(IAT->getElementType()); 459 else 460 Align = Context.getTypeAlign(D->getType()); 461 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) { 462 Align = std::max(Align, AA->getAlignment()); 463 } 464 GV->setAlignment(Align / 8); 465 466 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 467 setGlobalVisibility(GV, attr->getVisibility()); 468 // FIXME: else handle -fvisibility 469 470 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) { 471 // Prefaced with special LLVM marker to indicate that the name 472 // should not be munged. 473 GV->setName("\01" + ALA->getLabel()); 474 } 475 476 // Set the llvm linkage type as appropriate. 477 if (D->getStorageClass() == VarDecl::Static) 478 GV->setLinkage(llvm::Function::InternalLinkage); 479 else if (D->getAttr<DLLImportAttr>()) 480 GV->setLinkage(llvm::Function::DLLImportLinkage); 481 else if (D->getAttr<DLLExportAttr>()) 482 GV->setLinkage(llvm::Function::DLLExportLinkage); 483 else if (D->getAttr<WeakAttr>()) 484 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 485 else { 486 // FIXME: This isn't right. This should handle common linkage and other 487 // stuff. 488 switch (D->getStorageClass()) { 489 case VarDecl::Static: assert(0 && "This case handled above"); 490 case VarDecl::Auto: 491 case VarDecl::Register: 492 assert(0 && "Can't have auto or register globals"); 493 case VarDecl::None: 494 if (!D->getInit()) 495 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 496 break; 497 case VarDecl::Extern: 498 case VarDecl::PrivateExtern: 499 // todo: common 500 break; 501 } 502 } 503 504 // Emit global variable debug information. 505 CGDebugInfo *DI = getDebugInfo(); 506 if(DI) { 507 if(D->getLocation().isValid()) 508 DI->setLocation(D->getLocation()); 509 DI->EmitGlobalVariable(GV, D); 510 } 511 } 512 513 llvm::GlobalValue * 514 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) { 515 // FIXME: param attributes for sext/zext etc. 516 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) { 517 assert(!D->getBody() && "Unexpected alias attr on function with body."); 518 519 const std::string& aliaseeName = AA->getAliasee(); 520 llvm::Function *aliasee = getModule().getFunction(aliaseeName); 521 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(), 522 llvm::Function::ExternalLinkage, 523 D->getName(), 524 aliasee, 525 &getModule()); 526 SetGlobalValueAttributes(D, alias); 527 return alias; 528 } else { 529 const llvm::Type *Ty = getTypes().ConvertType(D->getType()); 530 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty); 531 llvm::Function *F = llvm::Function::Create(FTy, 532 llvm::Function::ExternalLinkage, 533 D->getName(), &getModule()); 534 535 SetFunctionAttributes(D, F, FTy); 536 return F; 537 } 538 } 539 540 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) { 541 QualType ASTTy = D->getType(); 542 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 543 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 544 545 // Lookup the entry, lazily creating it if necessary. 546 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()]; 547 if (!Entry) 548 Entry = EmitForwardFunctionDefinition(D); 549 550 return llvm::ConstantExpr::getBitCast(Entry, PTy); 551 } 552 553 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) { 554 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()]; 555 if (!Entry) { 556 Entry = EmitForwardFunctionDefinition(D); 557 } else { 558 // If the types mismatch then we have to rewrite the definition. 559 const llvm::Type *Ty = getTypes().ConvertType(D->getType()); 560 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) { 561 // Otherwise, we have a definition after a prototype with the wrong type. 562 // F is the Function* for the one with the wrong type, we must make a new 563 // Function* and update everything that used F (a declaration) with the new 564 // Function* (which will be a definition). 565 // 566 // This happens if there is a prototype for a function (e.g. "int f()") and 567 // then a definition of a different type (e.g. "int f(int x)"). Start by 568 // making a new function of the correct type, RAUW, then steal the name. 569 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D); 570 NewFn->takeName(Entry); 571 572 // Replace uses of F with the Function we will endow with a body. 573 llvm::Constant *NewPtrForOldDecl = 574 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 575 Entry->replaceAllUsesWith(NewPtrForOldDecl); 576 577 // Ok, delete the old function now, which is dead. 578 // FIXME: Add GlobalValue->eraseFromParent(). 579 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration"); 580 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) { 581 F->eraseFromParent(); 582 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) { 583 GA->eraseFromParent(); 584 } else { 585 assert(0 && "Invalid global variable type."); 586 } 587 588 Entry = NewFn; 589 } 590 } 591 592 if (D->getAttr<AliasAttr>()) { 593 ; 594 } else { 595 llvm::Function *Fn = cast<llvm::Function>(Entry); 596 CodeGenFunction(*this).GenerateCode(D, Fn); 597 598 // Set attributes specific to definition. 599 // FIXME: This needs to be cleaned up by clearly emitting the 600 // declaration / definition at separate times. 601 if (!Features.Exceptions) 602 Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind); 603 604 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) { 605 AddGlobalCtor(Fn, CA->getPriority()); 606 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) { 607 AddGlobalDtor(Fn, DA->getPriority()); 608 } 609 } 610 } 611 612 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 613 // Make sure that this type is translated. 614 Types.UpdateCompletedType(TD); 615 } 616 617 618 /// getBuiltinLibFunction 619 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 620 if (BuiltinID > BuiltinFunctions.size()) 621 BuiltinFunctions.resize(BuiltinID); 622 623 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve 624 // a slot for it. 625 assert(BuiltinID && "Invalid Builtin ID"); 626 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1]; 627 if (FunctionSlot) 628 return FunctionSlot; 629 630 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn"); 631 632 // Get the name, skip over the __builtin_ prefix. 633 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10; 634 635 // Get the type for the builtin. 636 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context); 637 const llvm::FunctionType *Ty = 638 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 639 640 // FIXME: This has a serious problem with code like this: 641 // void abs() {} 642 // ... __builtin_abs(x); 643 // The two versions of abs will collide. The fix is for the builtin to win, 644 // and for the existing one to be turned into a constantexpr cast of the 645 // builtin. In the case where the existing one is a static function, it 646 // should just be renamed. 647 if (llvm::Function *Existing = getModule().getFunction(Name)) { 648 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) 649 return FunctionSlot = Existing; 650 assert(Existing == 0 && "FIXME: Name collision"); 651 } 652 653 // FIXME: param attributes for sext/zext etc. 654 return FunctionSlot = 655 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name, 656 &getModule()); 657 } 658 659 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 660 unsigned NumTys) { 661 return llvm::Intrinsic::getDeclaration(&getModule(), 662 (llvm::Intrinsic::ID)IID, Tys, NumTys); 663 } 664 665 llvm::Function *CodeGenModule::getMemCpyFn() { 666 if (MemCpyFn) return MemCpyFn; 667 llvm::Intrinsic::ID IID; 668 switch (Context.Target.getPointerWidth(0)) { 669 default: assert(0 && "Unknown ptr width"); 670 case 32: IID = llvm::Intrinsic::memcpy_i32; break; 671 case 64: IID = llvm::Intrinsic::memcpy_i64; break; 672 } 673 return MemCpyFn = getIntrinsic(IID); 674 } 675 676 llvm::Function *CodeGenModule::getMemMoveFn() { 677 if (MemMoveFn) return MemMoveFn; 678 llvm::Intrinsic::ID IID; 679 switch (Context.Target.getPointerWidth(0)) { 680 default: assert(0 && "Unknown ptr width"); 681 case 32: IID = llvm::Intrinsic::memmove_i32; break; 682 case 64: IID = llvm::Intrinsic::memmove_i64; break; 683 } 684 return MemMoveFn = getIntrinsic(IID); 685 } 686 687 llvm::Function *CodeGenModule::getMemSetFn() { 688 if (MemSetFn) return MemSetFn; 689 llvm::Intrinsic::ID IID; 690 switch (Context.Target.getPointerWidth(0)) { 691 default: assert(0 && "Unknown ptr width"); 692 case 32: IID = llvm::Intrinsic::memset_i32; break; 693 case 64: IID = llvm::Intrinsic::memset_i64; break; 694 } 695 return MemSetFn = getIntrinsic(IID); 696 } 697 698 // We still need to work out the details of handling UTF-16. 699 // See: <rdr://2996215> 700 llvm::Constant *CodeGenModule:: 701 GetAddrOfConstantCFString(const std::string &str) { 702 llvm::StringMapEntry<llvm::Constant *> &Entry = 703 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 704 705 if (Entry.getValue()) 706 return Entry.getValue(); 707 708 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 709 llvm::Constant *Zeros[] = { Zero, Zero }; 710 711 if (!CFConstantStringClassRef) { 712 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 713 Ty = llvm::ArrayType::get(Ty, 0); 714 715 // FIXME: This is fairly broken if 716 // __CFConstantStringClassReference is already defined, in that it 717 // will get renamed and the user will most likely see an opaque 718 // error message. This is a general issue with relying on 719 // particular names. 720 llvm::GlobalVariable *GV = 721 new llvm::GlobalVariable(Ty, false, 722 llvm::GlobalVariable::ExternalLinkage, 0, 723 "__CFConstantStringClassReference", 724 &getModule()); 725 726 // Decay array -> ptr 727 CFConstantStringClassRef = 728 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 729 } 730 731 std::vector<llvm::Constant*> Fields(4); 732 733 // Class pointer. 734 Fields[0] = CFConstantStringClassRef; 735 736 // Flags. 737 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 738 Fields[1] = llvm::ConstantInt::get(Ty, 0x07C8); 739 740 // String pointer. 741 llvm::Constant *C = llvm::ConstantArray::get(str); 742 C = new llvm::GlobalVariable(C->getType(), true, 743 llvm::GlobalValue::InternalLinkage, 744 C, ".str", &getModule()); 745 Fields[2] = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); 746 747 // String length. 748 Ty = getTypes().ConvertType(getContext().LongTy); 749 Fields[3] = llvm::ConstantInt::get(Ty, str.length()); 750 751 // The struct. 752 Ty = getTypes().ConvertType(getContext().getCFConstantStringType()); 753 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields); 754 llvm::GlobalVariable *GV = 755 new llvm::GlobalVariable(C->getType(), true, 756 llvm::GlobalVariable::InternalLinkage, 757 C, "", &getModule()); 758 759 GV->setSection("__DATA,__cfstring"); 760 Entry.setValue(GV); 761 762 return GV; 763 } 764 765 /// GetStringForStringLiteral - Return the appropriate bytes for a 766 /// string literal, properly padded to match the literal type. 767 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 768 if (E->isWide()) { 769 ErrorUnsupported(E, "wide string"); 770 return "FIXME"; 771 } 772 773 const char *StrData = E->getStrData(); 774 unsigned Len = E->getByteLength(); 775 776 const ConstantArrayType *CAT = 777 getContext().getAsConstantArrayType(E->getType()); 778 assert(CAT && "String isn't pointer or array!"); 779 780 // Resize the string to the right size 781 // FIXME: What about wchar_t strings? 782 std::string Str(StrData, StrData+Len); 783 uint64_t RealLen = CAT->getSize().getZExtValue(); 784 Str.resize(RealLen, '\0'); 785 786 return Str; 787 } 788 789 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 790 /// constant array for the given string literal. 791 llvm::Constant * 792 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 793 // FIXME: This can be more efficient. 794 return GetAddrOfConstantString(GetStringForStringLiteral(S)); 795 } 796 797 /// GenerateWritableString -- Creates storage for a string literal. 798 static llvm::Constant *GenerateStringLiteral(const std::string &str, 799 bool constant, 800 CodeGenModule &CGM) { 801 // Create Constant for this string literal. Don't add a '\0'. 802 llvm::Constant *C = llvm::ConstantArray::get(str, false); 803 804 // Create a global variable for this string 805 C = new llvm::GlobalVariable(C->getType(), constant, 806 llvm::GlobalValue::InternalLinkage, 807 C, ".str", &CGM.getModule()); 808 809 return C; 810 } 811 812 /// GetAddrOfConstantString - Returns a pointer to a character array 813 /// containing the literal. This contents are exactly that of the 814 /// given string, i.e. it will not be null terminated automatically; 815 /// see GetAddrOfConstantCString. Note that whether the result is 816 /// actually a pointer to an LLVM constant depends on 817 /// Feature.WriteableStrings. 818 /// 819 /// The result has pointer to array type. 820 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) { 821 // Don't share any string literals if writable-strings is turned on. 822 if (Features.WritableStrings) 823 return GenerateStringLiteral(str, false, *this); 824 825 llvm::StringMapEntry<llvm::Constant *> &Entry = 826 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 827 828 if (Entry.getValue()) 829 return Entry.getValue(); 830 831 // Create a global variable for this. 832 llvm::Constant *C = GenerateStringLiteral(str, true, *this); 833 Entry.setValue(C); 834 return C; 835 } 836 837 /// GetAddrOfConstantCString - Returns a pointer to a character 838 /// array containing the literal and a terminating '\-' 839 /// character. The result has pointer to array type. 840 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str) { 841 return GetAddrOfConstantString(str + "\0"); 842 } 843 844 /// EmitObjCPropertyImplementations - Emit information for synthesized 845 /// properties for an implementation. 846 void CodeGenModule::EmitObjCPropertyImplementations(const 847 ObjCImplementationDecl *D) { 848 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(), 849 e = D->propimpl_end(); i != e; ++i) { 850 ObjCPropertyImplDecl *PID = *i; 851 852 // Dynamic is just for type-checking. 853 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 854 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 855 856 // Determine which methods need to be implemented, some may have 857 // been overridden. Note that ::isSynthesized is not the method 858 // we want, that just indicates if the decl came from a 859 // property. What we want to know is if the method is defined in 860 // this implementation. 861 if (!D->getInstanceMethod(PD->getGetterName())) 862 CodeGenFunction(*this).GenerateObjCGetter(PID); 863 if (!PD->isReadOnly() && 864 !D->getInstanceMethod(PD->getSetterName())) 865 CodeGenFunction(*this).GenerateObjCSetter(PID); 866 } 867 } 868 } 869 870 /// EmitTopLevelDecl - Emit code for a single top level declaration. 871 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 872 // If an error has occurred, stop code generation, but continue 873 // parsing and semantic analysis (to ensure all warnings and errors 874 // are emitted). 875 if (Diags.hasErrorOccurred()) 876 return; 877 878 switch (D->getKind()) { 879 case Decl::Function: 880 case Decl::Var: 881 EmitGlobal(cast<ValueDecl>(D)); 882 break; 883 884 case Decl::Namespace: 885 ErrorUnsupported(D, "namespace"); 886 break; 887 888 // Objective-C Decls 889 890 // Forward declarations, no (immediate) code generation. 891 case Decl::ObjCClass: 892 case Decl::ObjCCategory: 893 case Decl::ObjCForwardProtocol: 894 case Decl::ObjCInterface: 895 break; 896 897 case Decl::ObjCProtocol: 898 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 899 break; 900 901 case Decl::ObjCCategoryImpl: 902 // Categories have properties but don't support synthesize so we 903 // can ignore them here. 904 905 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 906 break; 907 908 case Decl::ObjCImplementation: { 909 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 910 EmitObjCPropertyImplementations(OMD); 911 Runtime->GenerateClass(OMD); 912 break; 913 } 914 case Decl::ObjCMethod: { 915 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 916 // If this is not a prototype, emit the body. 917 if (OMD->getBody()) 918 CodeGenFunction(*this).GenerateObjCMethod(OMD); 919 break; 920 } 921 case Decl::ObjCCompatibleAlias: 922 ErrorUnsupported(D, "Objective-C compatible alias"); 923 break; 924 925 case Decl::LinkageSpec: { 926 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D); 927 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx) 928 ErrorUnsupported(LSD, "linkage spec"); 929 // FIXME: implement C++ linkage, C linkage works mostly by C 930 // language reuse already. 931 break; 932 } 933 934 case Decl::FileScopeAsm: { 935 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 936 std::string AsmString(AD->getAsmString()->getStrData(), 937 AD->getAsmString()->getByteLength()); 938 939 const std::string &S = getModule().getModuleInlineAsm(); 940 if (S.empty()) 941 getModule().setModuleInlineAsm(AsmString); 942 else 943 getModule().setModuleInlineAsm(S + '\n' + AsmString); 944 break; 945 } 946 947 default: 948 // Make sure we handled everything we should, every other kind is 949 // a non-top-level decl. FIXME: Would be nice to have an 950 // isTopLevelDeclKind function. Need to recode Decl::Kind to do 951 // that easily. 952 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 953 } 954 } 955 956