1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===// 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 #include "llvm/CodeGen/MachineModuleInfo.h" 11 12 #include "llvm/Constants.h" 13 #include "llvm/Analysis/ValueTracking.h" 14 #include "llvm/CodeGen/MachineFunctionPass.h" 15 #include "llvm/CodeGen/MachineFunction.h" 16 #include "llvm/CodeGen/MachineLocation.h" 17 #include "llvm/CodeGen/MachineDebugInfoDesc.h" 18 #include "llvm/Target/TargetInstrInfo.h" 19 #include "llvm/Target/TargetMachine.h" 20 #include "llvm/Target/TargetOptions.h" 21 #include "llvm/DerivedTypes.h" 22 #include "llvm/GlobalVariable.h" 23 #include "llvm/Intrinsics.h" 24 #include "llvm/Instructions.h" 25 #include "llvm/Module.h" 26 #include "llvm/Support/Dwarf.h" 27 #include "llvm/Support/Streams.h" 28 using namespace llvm; 29 using namespace llvm::dwarf; 30 31 // Handle the Pass registration stuff necessary to use TargetData's. 32 static RegisterPass<MachineModuleInfo> 33 X("machinemoduleinfo", "Module Information"); 34 char MachineModuleInfo::ID = 0; 35 36 //===----------------------------------------------------------------------===// 37 38 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the 39 /// specified value in their initializer somewhere. 40 static void 41 getGlobalVariablesUsing(Value *V, SmallVectorImpl<GlobalVariable*> &Result) { 42 // Scan though value users. 43 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) { 44 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) { 45 // If the user is a GlobalVariable then add to result. 46 Result.push_back(GV); 47 } else if (Constant *C = dyn_cast<Constant>(*I)) { 48 // If the user is a constant variable then scan its users 49 getGlobalVariablesUsing(C, Result); 50 } 51 } 52 } 53 54 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the 55 /// named GlobalVariable. 56 static void 57 getGlobalVariablesUsing(Module &M, const std::string &RootName, 58 SmallVectorImpl<GlobalVariable*> &Result) { 59 std::vector<const Type*> FieldTypes; 60 FieldTypes.push_back(Type::Int32Ty); 61 FieldTypes.push_back(Type::Int32Ty); 62 63 // Get the GlobalVariable root. 64 GlobalVariable *UseRoot = M.getGlobalVariable(RootName, 65 StructType::get(FieldTypes)); 66 67 // If present and linkonce then scan for users. 68 if (UseRoot && UseRoot->hasLinkOnceLinkage()) 69 getGlobalVariablesUsing(UseRoot, Result); 70 } 71 72 /// isStringValue - Return true if the given value can be coerced to a string. 73 /// 74 static bool isStringValue(Value *V) { 75 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 76 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) { 77 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 78 return Init->isString(); 79 } 80 } else if (Constant *C = dyn_cast<Constant>(V)) { 81 if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) 82 return isStringValue(GV); 83 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 84 if (CE->getOpcode() == Instruction::GetElementPtr) { 85 if (CE->getNumOperands() == 3 && 86 cast<Constant>(CE->getOperand(1))->isNullValue() && 87 isa<ConstantInt>(CE->getOperand(2))) { 88 return isStringValue(CE->getOperand(0)); 89 } 90 } 91 } 92 } 93 return false; 94 } 95 96 /// getGlobalVariable - Return either a direct or cast Global value. 97 /// 98 static GlobalVariable *getGlobalVariable(Value *V) { 99 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 100 return GV; 101 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 102 if (CE->getOpcode() == Instruction::BitCast) { 103 return dyn_cast<GlobalVariable>(CE->getOperand(0)); 104 } else if (CE->getOpcode() == Instruction::GetElementPtr) { 105 for (unsigned int i=1; i<CE->getNumOperands(); i++) { 106 if (!CE->getOperand(i)->isNullValue()) 107 return NULL; 108 } 109 return dyn_cast<GlobalVariable>(CE->getOperand(0)); 110 } 111 } 112 return NULL; 113 } 114 115 /// isGlobalVariable - Return true if the given value can be coerced to a 116 /// GlobalVariable. 117 static bool isGlobalVariable(Value *V) { 118 if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) { 119 return true; 120 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 121 if (CE->getOpcode() == Instruction::BitCast) { 122 return isa<GlobalVariable>(CE->getOperand(0)); 123 } else if (CE->getOpcode() == Instruction::GetElementPtr) { 124 for (unsigned int i=1; i<CE->getNumOperands(); i++) { 125 if (!CE->getOperand(i)->isNullValue()) 126 return false; 127 } 128 return isa<GlobalVariable>(CE->getOperand(0)); 129 } 130 } 131 return false; 132 } 133 134 //===----------------------------------------------------------------------===// 135 136 /// ApplyToFields - Target the visitor to each field of the debug information 137 /// descriptor. 138 void DIVisitor::ApplyToFields(DebugInfoDesc *DD) { 139 DD->ApplyToFields(this); 140 } 141 142 namespace { 143 144 //===----------------------------------------------------------------------===// 145 /// DICountVisitor - This DIVisitor counts all the fields in the supplied debug 146 /// the supplied DebugInfoDesc. 147 class DICountVisitor : public DIVisitor { 148 private: 149 unsigned Count; // Running count of fields. 150 151 public: 152 DICountVisitor() : DIVisitor(), Count(0) {} 153 154 // Accessors. 155 unsigned getCount() const { return Count; } 156 157 /// Apply - Count each of the fields. 158 /// 159 virtual void Apply(int &Field) { ++Count; } 160 virtual void Apply(unsigned &Field) { ++Count; } 161 virtual void Apply(int64_t &Field) { ++Count; } 162 virtual void Apply(uint64_t &Field) { ++Count; } 163 virtual void Apply(bool &Field) { ++Count; } 164 virtual void Apply(std::string &Field) { ++Count; } 165 virtual void Apply(DebugInfoDesc *&Field) { ++Count; } 166 virtual void Apply(GlobalVariable *&Field) { ++Count; } 167 virtual void Apply(std::vector<DebugInfoDesc *> &Field) { 168 ++Count; 169 } 170 }; 171 172 //===----------------------------------------------------------------------===// 173 /// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the 174 /// supplied DebugInfoDesc. 175 class DIDeserializeVisitor : public DIVisitor { 176 private: 177 DIDeserializer &DR; // Active deserializer. 178 unsigned I; // Current operand index. 179 ConstantStruct *CI; // GlobalVariable constant initializer. 180 181 public: 182 DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV) 183 : DIVisitor(), DR(D), I(0), CI(cast<ConstantStruct>(GV->getInitializer())) 184 {} 185 186 /// Apply - Set the value of each of the fields. 187 /// 188 virtual void Apply(int &Field) { 189 Constant *C = CI->getOperand(I++); 190 Field = cast<ConstantInt>(C)->getSExtValue(); 191 } 192 virtual void Apply(unsigned &Field) { 193 Constant *C = CI->getOperand(I++); 194 Field = cast<ConstantInt>(C)->getZExtValue(); 195 } 196 virtual void Apply(int64_t &Field) { 197 Constant *C = CI->getOperand(I++); 198 Field = cast<ConstantInt>(C)->getSExtValue(); 199 } 200 virtual void Apply(uint64_t &Field) { 201 Constant *C = CI->getOperand(I++); 202 Field = cast<ConstantInt>(C)->getZExtValue(); 203 } 204 virtual void Apply(bool &Field) { 205 Constant *C = CI->getOperand(I++); 206 Field = cast<ConstantInt>(C)->getZExtValue(); 207 } 208 virtual void Apply(std::string &Field) { 209 Constant *C = CI->getOperand(I++); 210 // Fills in the string if it succeeds 211 if (!GetConstantStringInfo(C, Field)) 212 Field.clear(); 213 } 214 virtual void Apply(DebugInfoDesc *&Field) { 215 Constant *C = CI->getOperand(I++); 216 Field = DR.Deserialize(C); 217 } 218 virtual void Apply(GlobalVariable *&Field) { 219 Constant *C = CI->getOperand(I++); 220 Field = getGlobalVariable(C); 221 } 222 virtual void Apply(std::vector<DebugInfoDesc *> &Field) { 223 Field.resize(0); 224 Constant *C = CI->getOperand(I++); 225 GlobalVariable *GV = getGlobalVariable(C); 226 if (GV->hasInitializer()) { 227 if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) { 228 for (unsigned i = 0, N = CA->getNumOperands(); i < N; ++i) { 229 GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i)); 230 DebugInfoDesc *DE = DR.Deserialize(GVE); 231 Field.push_back(DE); 232 } 233 } else if (GV->getInitializer()->isNullValue()) { 234 if (const ArrayType *T = 235 dyn_cast<ArrayType>(GV->getType()->getElementType())) { 236 Field.resize(T->getNumElements()); 237 } 238 } 239 } 240 } 241 }; 242 243 //===----------------------------------------------------------------------===// 244 /// DISerializeVisitor - This DIVisitor serializes all the fields in 245 /// the supplied DebugInfoDesc. 246 class DISerializeVisitor : public DIVisitor { 247 private: 248 DISerializer &SR; // Active serializer. 249 std::vector<Constant*> &Elements; // Element accumulator. 250 251 public: 252 DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E) 253 : DIVisitor() 254 , SR(S) 255 , Elements(E) 256 {} 257 258 /// Apply - Set the value of each of the fields. 259 /// 260 virtual void Apply(int &Field) { 261 Elements.push_back(ConstantInt::get(Type::Int32Ty, int32_t(Field))); 262 } 263 virtual void Apply(unsigned &Field) { 264 Elements.push_back(ConstantInt::get(Type::Int32Ty, uint32_t(Field))); 265 } 266 virtual void Apply(int64_t &Field) { 267 Elements.push_back(ConstantInt::get(Type::Int64Ty, int64_t(Field))); 268 } 269 virtual void Apply(uint64_t &Field) { 270 Elements.push_back(ConstantInt::get(Type::Int64Ty, uint64_t(Field))); 271 } 272 virtual void Apply(bool &Field) { 273 Elements.push_back(ConstantInt::get(Type::Int1Ty, Field)); 274 } 275 virtual void Apply(std::string &Field) { 276 Elements.push_back(SR.getString(Field)); 277 } 278 virtual void Apply(DebugInfoDesc *&Field) { 279 GlobalVariable *GV = NULL; 280 281 // If non-NULL then convert to global. 282 if (Field) GV = SR.Serialize(Field); 283 284 // FIXME - At some point should use specific type. 285 const PointerType *EmptyTy = SR.getEmptyStructPtrType(); 286 287 if (GV) { 288 // Set to pointer to global. 289 Elements.push_back(ConstantExpr::getBitCast(GV, EmptyTy)); 290 } else { 291 // Use NULL. 292 Elements.push_back(ConstantPointerNull::get(EmptyTy)); 293 } 294 } 295 virtual void Apply(GlobalVariable *&Field) { 296 const PointerType *EmptyTy = SR.getEmptyStructPtrType(); 297 if (Field) { 298 Elements.push_back(ConstantExpr::getBitCast(Field, EmptyTy)); 299 } else { 300 Elements.push_back(ConstantPointerNull::get(EmptyTy)); 301 } 302 } 303 virtual void Apply(std::vector<DebugInfoDesc *> &Field) { 304 const PointerType *EmptyTy = SR.getEmptyStructPtrType(); 305 unsigned N = Field.size(); 306 ArrayType *AT = ArrayType::get(EmptyTy, N); 307 std::vector<Constant *> ArrayElements; 308 309 for (unsigned i = 0, N = Field.size(); i < N; ++i) { 310 if (DebugInfoDesc *Element = Field[i]) { 311 GlobalVariable *GVE = SR.Serialize(Element); 312 Constant *CE = ConstantExpr::getBitCast(GVE, EmptyTy); 313 ArrayElements.push_back(cast<Constant>(CE)); 314 } else { 315 ArrayElements.push_back(ConstantPointerNull::get(EmptyTy)); 316 } 317 } 318 319 Constant *CA = ConstantArray::get(AT, ArrayElements); 320 GlobalVariable *CAGV = new GlobalVariable(AT, true, 321 GlobalValue::InternalLinkage, 322 CA, "llvm.dbg.array", 323 SR.getModule()); 324 CAGV->setSection("llvm.metadata"); 325 Constant *CAE = ConstantExpr::getBitCast(CAGV, EmptyTy); 326 Elements.push_back(CAE); 327 } 328 }; 329 330 //===----------------------------------------------------------------------===// 331 /// DIGetTypesVisitor - This DIVisitor gathers all the field types in 332 /// the supplied DebugInfoDesc. 333 class DIGetTypesVisitor : public DIVisitor { 334 private: 335 DISerializer &SR; // Active serializer. 336 std::vector<const Type*> &Fields; // Type accumulator. 337 338 public: 339 DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F) 340 : DIVisitor() 341 , SR(S) 342 , Fields(F) 343 {} 344 345 /// Apply - Set the value of each of the fields. 346 /// 347 virtual void Apply(int &Field) { 348 Fields.push_back(Type::Int32Ty); 349 } 350 virtual void Apply(unsigned &Field) { 351 Fields.push_back(Type::Int32Ty); 352 } 353 virtual void Apply(int64_t &Field) { 354 Fields.push_back(Type::Int64Ty); 355 } 356 virtual void Apply(uint64_t &Field) { 357 Fields.push_back(Type::Int64Ty); 358 } 359 virtual void Apply(bool &Field) { 360 Fields.push_back(Type::Int1Ty); 361 } 362 virtual void Apply(std::string &Field) { 363 Fields.push_back(SR.getStrPtrType()); 364 } 365 virtual void Apply(DebugInfoDesc *&Field) { 366 // FIXME - At some point should use specific type. 367 const PointerType *EmptyTy = SR.getEmptyStructPtrType(); 368 Fields.push_back(EmptyTy); 369 } 370 virtual void Apply(GlobalVariable *&Field) { 371 const PointerType *EmptyTy = SR.getEmptyStructPtrType(); 372 Fields.push_back(EmptyTy); 373 } 374 virtual void Apply(std::vector<DebugInfoDesc *> &Field) { 375 const PointerType *EmptyTy = SR.getEmptyStructPtrType(); 376 Fields.push_back(EmptyTy); 377 } 378 }; 379 380 //===----------------------------------------------------------------------===// 381 /// DIVerifyVisitor - This DIVisitor verifies all the field types against 382 /// a constant initializer. 383 class DIVerifyVisitor : public DIVisitor { 384 private: 385 DIVerifier &VR; // Active verifier. 386 bool IsValid; // Validity status. 387 unsigned I; // Current operand index. 388 ConstantStruct *CI; // GlobalVariable constant initializer. 389 390 public: 391 DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV) 392 : DIVisitor() 393 , VR(V) 394 , IsValid(true) 395 , I(0) 396 , CI(cast<ConstantStruct>(GV->getInitializer())) 397 { 398 } 399 400 // Accessors. 401 bool isValid() const { return IsValid; } 402 403 /// Apply - Set the value of each of the fields. 404 /// 405 virtual void Apply(int &Field) { 406 Constant *C = CI->getOperand(I++); 407 IsValid = IsValid && isa<ConstantInt>(C); 408 } 409 virtual void Apply(unsigned &Field) { 410 Constant *C = CI->getOperand(I++); 411 IsValid = IsValid && isa<ConstantInt>(C); 412 } 413 virtual void Apply(int64_t &Field) { 414 Constant *C = CI->getOperand(I++); 415 IsValid = IsValid && isa<ConstantInt>(C); 416 } 417 virtual void Apply(uint64_t &Field) { 418 Constant *C = CI->getOperand(I++); 419 IsValid = IsValid && isa<ConstantInt>(C); 420 } 421 virtual void Apply(bool &Field) { 422 Constant *C = CI->getOperand(I++); 423 IsValid = IsValid && isa<ConstantInt>(C) && C->getType() == Type::Int1Ty; 424 } 425 virtual void Apply(std::string &Field) { 426 Constant *C = CI->getOperand(I++); 427 IsValid = IsValid && 428 (!C || isStringValue(C) || C->isNullValue()); 429 } 430 virtual void Apply(DebugInfoDesc *&Field) { 431 // FIXME - Prepare the correct descriptor. 432 Constant *C = CI->getOperand(I++); 433 IsValid = IsValid && isGlobalVariable(C); 434 } 435 virtual void Apply(GlobalVariable *&Field) { 436 Constant *C = CI->getOperand(I++); 437 IsValid = IsValid && isGlobalVariable(C); 438 } 439 virtual void Apply(std::vector<DebugInfoDesc *> &Field) { 440 Constant *C = CI->getOperand(I++); 441 IsValid = IsValid && isGlobalVariable(C); 442 if (!IsValid) return; 443 444 GlobalVariable *GV = getGlobalVariable(C); 445 IsValid = IsValid && GV && GV->hasInitializer(); 446 if (!IsValid) return; 447 448 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer()); 449 IsValid = IsValid && CA; 450 if (!IsValid) return; 451 452 for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) { 453 IsValid = IsValid && isGlobalVariable(CA->getOperand(i)); 454 if (!IsValid) return; 455 456 GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i)); 457 VR.Verify(GVE); 458 } 459 } 460 }; 461 462 } 463 464 //===----------------------------------------------------------------------===// 465 466 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) { 467 return Deserialize(getGlobalVariable(V)); 468 } 469 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) { 470 // Handle NULL. 471 if (!GV) return NULL; 472 473 // Check to see if it has been already deserialized. 474 DebugInfoDesc *&Slot = GlobalDescs[GV]; 475 if (Slot) return Slot; 476 477 // Get the Tag from the global. 478 unsigned Tag = DebugInfoDesc::TagFromGlobal(GV); 479 480 // Create an empty instance of the correct sort. 481 Slot = DebugInfoDesc::DescFactory(Tag); 482 483 // If not a user defined descriptor. 484 if (Slot) { 485 // Deserialize the fields. 486 DIDeserializeVisitor DRAM(*this, GV); 487 DRAM.ApplyToFields(Slot); 488 } 489 490 return Slot; 491 } 492 493 //===----------------------------------------------------------------------===// 494 495 /// getStrPtrType - Return a "sbyte *" type. 496 /// 497 const PointerType *DISerializer::getStrPtrType() { 498 // If not already defined. 499 if (!StrPtrTy) { 500 // Construct the pointer to signed bytes. 501 StrPtrTy = PointerType::getUnqual(Type::Int8Ty); 502 } 503 504 return StrPtrTy; 505 } 506 507 /// getEmptyStructPtrType - Return a "{ }*" type. 508 /// 509 const PointerType *DISerializer::getEmptyStructPtrType() { 510 // If not already defined. 511 if (EmptyStructPtrTy) return EmptyStructPtrTy; 512 513 // Construct the pointer to empty structure type. 514 const StructType *EmptyStructTy = 515 StructType::get(std::vector<const Type*>()); 516 return EmptyStructPtrTy; 517 } 518 519 /// getTagType - Return the type describing the specified descriptor (via tag.) 520 /// 521 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) { 522 // Attempt to get the previously defined type. 523 StructType *&Ty = TagTypes[DD->getTag()]; 524 525 // If not already defined. 526 if (!Ty) { 527 // Set up fields vector. 528 std::vector<const Type*> Fields; 529 // Get types of fields. 530 DIGetTypesVisitor GTAM(*this, Fields); 531 GTAM.ApplyToFields(DD); 532 533 // Construct structured type. 534 Ty = StructType::get(Fields); 535 536 // Register type name with module. 537 M->addTypeName(DD->getTypeString(), Ty); 538 } 539 540 return Ty; 541 } 542 543 /// getString - Construct the string as constant string global. 544 /// 545 Constant *DISerializer::getString(const std::string &String) { 546 // Check string cache for previous edition. 547 Constant *&Slot = StringCache[String.c_str()]; 548 549 // Return Constant if previously defined. 550 if (Slot) return Slot; 551 552 // If empty string then use a sbyte* null instead. 553 if (String.empty()) { 554 Slot = ConstantPointerNull::get(getStrPtrType()); 555 } else { 556 // Construct string as an llvm constant. 557 Constant *ConstStr = ConstantArray::get(String); 558 559 // Otherwise create and return a new string global. 560 GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true, 561 GlobalVariable::InternalLinkage, 562 ConstStr, ".str", M); 563 StrGV->setSection("llvm.metadata"); 564 565 // Convert to generic string pointer. 566 Slot = ConstantExpr::getBitCast(StrGV, getStrPtrType()); 567 } 568 569 return Slot; 570 571 } 572 573 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable 574 /// so that it can be serialized to a .bc or .ll file. 575 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) { 576 // Check if the DebugInfoDesc is already in the map. 577 GlobalVariable *&Slot = DescGlobals[DD]; 578 579 // See if DebugInfoDesc exists, if so return prior GlobalVariable. 580 if (Slot) return Slot; 581 582 // Get the type associated with the Tag. 583 const StructType *Ty = getTagType(DD); 584 585 // Create the GlobalVariable early to prevent infinite recursion. 586 GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(), 587 NULL, DD->getDescString(), M); 588 GV->setSection("llvm.metadata"); 589 590 // Insert new GlobalVariable in DescGlobals map. 591 Slot = GV; 592 593 // Set up elements vector 594 std::vector<Constant*> Elements; 595 // Add fields. 596 DISerializeVisitor SRAM(*this, Elements); 597 SRAM.ApplyToFields(DD); 598 599 // Set the globals initializer. 600 GV->setInitializer(ConstantStruct::get(Ty, Elements)); 601 602 return GV; 603 } 604 605 /// addDescriptor - Directly connect DD with existing GV. 606 void DISerializer::addDescriptor(DebugInfoDesc *DD, 607 GlobalVariable *GV) { 608 DescGlobals[DD] = GV; 609 } 610 611 //===----------------------------------------------------------------------===// 612 613 /// Verify - Return true if the GlobalVariable appears to be a valid 614 /// serialization of a DebugInfoDesc. 615 bool DIVerifier::Verify(Value *V) { 616 return !V || Verify(getGlobalVariable(V)); 617 } 618 bool DIVerifier::Verify(GlobalVariable *GV) { 619 // NULLs are valid. 620 if (!GV) return true; 621 622 // Check prior validity. 623 unsigned &ValiditySlot = Validity[GV]; 624 625 // If visited before then use old state. 626 if (ValiditySlot) return ValiditySlot == Valid; 627 628 // Assume validity for the time being (recursion.) 629 ValiditySlot = Valid; 630 631 // Make sure the global is internal or link once (anchor.) 632 if (GV->getLinkage() != GlobalValue::InternalLinkage && 633 GV->getLinkage() != GlobalValue::LinkOnceLinkage) { 634 ValiditySlot = Invalid; 635 return false; 636 } 637 638 // Get the Tag. 639 unsigned Tag = DebugInfoDesc::TagFromGlobal(GV); 640 641 // Check for user defined descriptors. 642 if (Tag == DW_TAG_invalid) { 643 ValiditySlot = Valid; 644 return true; 645 } 646 647 // Get the Version. 648 unsigned Version = DebugInfoDesc::VersionFromGlobal(GV); 649 650 // Check for version mismatch. 651 if (Version != LLVMDebugVersion) { 652 ValiditySlot = Invalid; 653 return false; 654 } 655 656 // Construct an empty DebugInfoDesc. 657 DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag); 658 659 // Allow for user defined descriptors. 660 if (!DD) return true; 661 662 // Get the initializer constant. 663 ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer()); 664 665 // Get the operand count. 666 unsigned N = CI->getNumOperands(); 667 668 // Get the field count. 669 unsigned &CountSlot = Counts[Tag]; 670 if (!CountSlot) { 671 // Check the operand count to the field count 672 DICountVisitor CTAM; 673 CTAM.ApplyToFields(DD); 674 CountSlot = CTAM.getCount(); 675 } 676 677 // Field count must be at most equal operand count. 678 if (CountSlot > N) { 679 delete DD; 680 ValiditySlot = Invalid; 681 return false; 682 } 683 684 // Check each field for valid type. 685 DIVerifyVisitor VRAM(*this, GV); 686 VRAM.ApplyToFields(DD); 687 688 // Release empty DebugInfoDesc. 689 delete DD; 690 691 // If fields are not valid. 692 if (!VRAM.isValid()) { 693 ValiditySlot = Invalid; 694 return false; 695 } 696 697 return true; 698 } 699 700 /// isVerified - Return true if the specified GV has already been 701 /// verified as a debug information descriptor. 702 bool DIVerifier::isVerified(GlobalVariable *GV) { 703 unsigned &ValiditySlot = Validity[GV]; 704 if (ValiditySlot) return ValiditySlot == Valid; 705 return false; 706 } 707 708 //===----------------------------------------------------------------------===// 709 710 DebugScope::~DebugScope() { 711 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i]; 712 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j]; 713 } 714 715 //===----------------------------------------------------------------------===// 716 717 MachineModuleInfo::MachineModuleInfo() 718 : ImmutablePass((intptr_t)&ID) 719 , DR() 720 , VR() 721 , CompileUnits() 722 , Directories() 723 , SourceFiles() 724 , Lines() 725 , LabelIDList() 726 , ScopeMap() 727 , RootScope(NULL) 728 , FrameMoves() 729 , LandingPads() 730 , Personalities() 731 , CallsEHReturn(0) 732 , CallsUnwindInit(0) 733 { 734 // Always emit "no personality" info 735 Personalities.push_back(NULL); 736 } 737 MachineModuleInfo::~MachineModuleInfo() { 738 739 } 740 741 /// doInitialization - Initialize the state for a new module. 742 /// 743 bool MachineModuleInfo::doInitialization() { 744 return false; 745 } 746 747 /// doFinalization - Tear down the state after completion of a module. 748 /// 749 bool MachineModuleInfo::doFinalization() { 750 return false; 751 } 752 753 /// BeginFunction - Begin gathering function meta information. 754 /// 755 void MachineModuleInfo::BeginFunction(MachineFunction *MF) { 756 // Coming soon. 757 } 758 759 /// EndFunction - Discard function meta information. 760 /// 761 void MachineModuleInfo::EndFunction() { 762 // Clean up scope information. 763 if (RootScope) { 764 delete RootScope; 765 ScopeMap.clear(); 766 RootScope = NULL; 767 } 768 769 // Clean up line info. 770 Lines.clear(); 771 772 // Clean up frame info. 773 FrameMoves.clear(); 774 775 // Clean up exception info. 776 LandingPads.clear(); 777 TypeInfos.clear(); 778 FilterIds.clear(); 779 FilterEnds.clear(); 780 CallsEHReturn = 0; 781 CallsUnwindInit = 0; 782 } 783 784 /// getDescFor - Convert a Value to a debug information descriptor. 785 /// 786 // FIXME - use new Value type when available. 787 DebugInfoDesc *MachineModuleInfo::getDescFor(Value *V) { 788 return DR.Deserialize(V); 789 } 790 791 /// AnalyzeModule - Scan the module for global debug information. 792 /// 793 void MachineModuleInfo::AnalyzeModule(Module &M) { 794 SetupCompileUnits(M); 795 796 // Insert functions in the llvm.used array into UsedFunctions. 797 GlobalVariable *GV = M.getGlobalVariable("llvm.used"); 798 if (!GV || !GV->hasInitializer()) return; 799 800 // Should be an array of 'i8*'. 801 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 802 if (InitList == 0) return; 803 804 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 805 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InitList->getOperand(i))) 806 if (CE->getOpcode() == Instruction::BitCast) 807 if (Function *F = dyn_cast<Function>(CE->getOperand(0))) 808 UsedFunctions.insert(F); 809 } 810 } 811 812 /// SetupCompileUnits - Set up the unique vector of compile units. 813 /// 814 void MachineModuleInfo::SetupCompileUnits(Module &M) { 815 std::vector<void*> CUList; 816 CompileUnitDesc CUD; 817 getAnchoredDescriptors(M, &CUD, CUList); 818 819 for (unsigned i = 0, N = CUList.size(); i < N; i++) 820 CompileUnits.insert((CompileUnitDesc*)CUList[i]); 821 } 822 823 /// getCompileUnits - Return a vector of debug compile units. 824 /// 825 const UniqueVector<CompileUnitDesc *> MachineModuleInfo::getCompileUnits()const{ 826 return CompileUnits; 827 } 828 829 /// getAnchoredDescriptors - Return a vector of anchored debug descriptors. 830 /// 831 void 832 MachineModuleInfo::getAnchoredDescriptors(Module &M, const AnchoredDesc *Desc, 833 std::vector<void*> &AnchoredDescs) { 834 SmallVector<GlobalVariable*, 64> Globals; 835 getGlobalVariablesUsing(M, Desc->getAnchorString(), Globals); 836 837 for (unsigned i = 0, N = Globals.size(); i < N; ++i) { 838 GlobalVariable *GV = Globals[i]; 839 840 // FIXME - In the short term, changes are too drastic to continue. 841 if (DebugInfoDesc::TagFromGlobal(GV) == Desc->getTag() && 842 DebugInfoDesc::VersionFromGlobal(GV) == LLVMDebugVersion) 843 AnchoredDescs.push_back(DR.Deserialize(GV)); 844 } 845 } 846 847 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the 848 /// named GlobalVariable. 849 void 850 MachineModuleInfo::getGlobalVariablesUsing(Module &M, 851 const std::string &RootName, 852 std::vector<GlobalVariable*> &Globals) { 853 return ::getGlobalVariablesUsing(M, RootName, Globals); 854 } 855 856 /// RecordSourceLine - Records location information and associates it with a 857 /// debug label. Returns a unique label ID used to generate a label and 858 /// provide correspondence to the source line list. 859 unsigned MachineModuleInfo::RecordSourceLine(unsigned Line, unsigned Column, 860 unsigned Source) { 861 unsigned ID = NextLabelID(); 862 Lines.push_back(SourceLineInfo(Line, Column, Source, ID)); 863 return ID; 864 } 865 866 /// RecordSource - Register a source file with debug info. Returns an source 867 /// ID. 868 unsigned MachineModuleInfo::RecordSource(const std::string &Directory, 869 const std::string &Source) { 870 unsigned DirectoryID = Directories.insert(Directory); 871 return SourceFiles.insert(SourceFileInfo(DirectoryID, Source)); 872 } 873 unsigned MachineModuleInfo::RecordSource(const CompileUnitDesc *CompileUnit) { 874 return RecordSource(CompileUnit->getDirectory(), 875 CompileUnit->getFileName()); 876 } 877 878 /// RecordRegionStart - Indicate the start of a region. 879 /// 880 unsigned MachineModuleInfo::RecordRegionStart(Value *V) { 881 // FIXME - need to be able to handle split scopes because of bb cloning. 882 DebugInfoDesc *ScopeDesc = DR.Deserialize(V); 883 DebugScope *Scope = getOrCreateScope(ScopeDesc); 884 unsigned ID = NextLabelID(); 885 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID); 886 return ID; 887 } 888 889 /// RecordRegionEnd - Indicate the end of a region. 890 /// 891 unsigned MachineModuleInfo::RecordRegionEnd(Value *V) { 892 // FIXME - need to be able to handle split scopes because of bb cloning. 893 DebugInfoDesc *ScopeDesc = DR.Deserialize(V); 894 DebugScope *Scope = getOrCreateScope(ScopeDesc); 895 unsigned ID = NextLabelID(); 896 Scope->setEndLabelID(ID); 897 return ID; 898 } 899 900 /// RecordVariable - Indicate the declaration of a local variable. 901 /// 902 void MachineModuleInfo::RecordVariable(GlobalValue *GV, unsigned FrameIndex) { 903 VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(GV)); 904 DebugScope *Scope = getOrCreateScope(VD->getContext()); 905 DebugVariable *DV = new DebugVariable(VD, FrameIndex); 906 Scope->AddVariable(DV); 907 } 908 909 /// getOrCreateScope - Returns the scope associated with the given descriptor. 910 /// 911 DebugScope *MachineModuleInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) { 912 DebugScope *&Slot = ScopeMap[ScopeDesc]; 913 if (!Slot) { 914 // FIXME - breaks down when the context is an inlined function. 915 DebugInfoDesc *ParentDesc = NULL; 916 if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) { 917 ParentDesc = Block->getContext(); 918 } 919 DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL; 920 Slot = new DebugScope(Parent, ScopeDesc); 921 if (Parent) { 922 Parent->AddScope(Slot); 923 } else if (RootScope) { 924 // FIXME - Add inlined function scopes to the root so we can delete 925 // them later. Long term, handle inlined functions properly. 926 RootScope->AddScope(Slot); 927 } else { 928 // First function is top level function. 929 RootScope = Slot; 930 } 931 } 932 return Slot; 933 } 934 935 //===-EH-------------------------------------------------------------------===// 936 937 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the 938 /// specified MachineBasicBlock. 939 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo 940 (MachineBasicBlock *LandingPad) { 941 unsigned N = LandingPads.size(); 942 for (unsigned i = 0; i < N; ++i) { 943 LandingPadInfo &LP = LandingPads[i]; 944 if (LP.LandingPadBlock == LandingPad) 945 return LP; 946 } 947 948 LandingPads.push_back(LandingPadInfo(LandingPad)); 949 return LandingPads[N]; 950 } 951 952 /// addInvoke - Provide the begin and end labels of an invoke style call and 953 /// associate it with a try landing pad block. 954 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad, 955 unsigned BeginLabel, unsigned EndLabel) { 956 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 957 LP.BeginLabels.push_back(BeginLabel); 958 LP.EndLabels.push_back(EndLabel); 959 } 960 961 /// addLandingPad - Provide the label of a try LandingPad block. 962 /// 963 unsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) { 964 unsigned LandingPadLabel = NextLabelID(); 965 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 966 LP.LandingPadLabel = LandingPadLabel; 967 return LandingPadLabel; 968 } 969 970 /// addPersonality - Provide the personality function for the exception 971 /// information. 972 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad, 973 Function *Personality) { 974 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 975 LP.Personality = Personality; 976 977 for (unsigned i = 0; i < Personalities.size(); ++i) 978 if (Personalities[i] == Personality) 979 return; 980 981 Personalities.push_back(Personality); 982 } 983 984 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad. 985 /// 986 void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad, 987 std::vector<GlobalVariable *> &TyInfo) { 988 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 989 for (unsigned N = TyInfo.size(); N; --N) 990 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 991 } 992 993 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad. 994 /// 995 void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad, 996 std::vector<GlobalVariable *> &TyInfo) { 997 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 998 std::vector<unsigned> IdsInFilter (TyInfo.size()); 999 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 1000 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 1001 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 1002 } 1003 1004 /// addCleanup - Add a cleanup action for a landing pad. 1005 /// 1006 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) { 1007 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 1008 LP.TypeIds.push_back(0); 1009 } 1010 1011 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing 1012 /// pads. 1013 void MachineModuleInfo::TidyLandingPads() { 1014 for (unsigned i = 0; i != LandingPads.size(); ) { 1015 LandingPadInfo &LandingPad = LandingPads[i]; 1016 LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel); 1017 1018 // Special case: we *should* emit LPs with null LP MBB. This indicates 1019 // "nounwind" case. 1020 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 1021 LandingPads.erase(LandingPads.begin() + i); 1022 continue; 1023 } 1024 1025 for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) { 1026 unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]); 1027 unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]); 1028 1029 if (!BeginLabel || !EndLabel) { 1030 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 1031 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 1032 continue; 1033 } 1034 1035 LandingPad.BeginLabels[j] = BeginLabel; 1036 LandingPad.EndLabels[j] = EndLabel; 1037 ++j; 1038 } 1039 1040 // Remove landing pads with no try-ranges. 1041 if (LandingPads[i].BeginLabels.empty()) { 1042 LandingPads.erase(LandingPads.begin() + i); 1043 continue; 1044 } 1045 1046 // If there is no landing pad, ensure that the list of typeids is empty. 1047 // If the only typeid is a cleanup, this is the same as having no typeids. 1048 if (!LandingPad.LandingPadBlock || 1049 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 1050 LandingPad.TypeIds.clear(); 1051 1052 ++i; 1053 } 1054 } 1055 1056 /// getTypeIDFor - Return the type id for the specified typeinfo. This is 1057 /// function wide. 1058 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) { 1059 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 1060 if (TypeInfos[i] == TI) return i + 1; 1061 1062 TypeInfos.push_back(TI); 1063 return TypeInfos.size(); 1064 } 1065 1066 /// getFilterIDFor - Return the filter id for the specified typeinfos. This is 1067 /// function wide. 1068 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) { 1069 // If the new filter coincides with the tail of an existing filter, then 1070 // re-use the existing filter. Folding filters more than this requires 1071 // re-ordering filters and/or their elements - probably not worth it. 1072 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 1073 E = FilterEnds.end(); I != E; ++I) { 1074 unsigned i = *I, j = TyIds.size(); 1075 1076 while (i && j) 1077 if (FilterIds[--i] != TyIds[--j]) 1078 goto try_next; 1079 1080 if (!j) 1081 // The new filter coincides with range [i, end) of the existing filter. 1082 return -(1 + i); 1083 1084 try_next:; 1085 } 1086 1087 // Add the new filter. 1088 int FilterID = -(1 + FilterIds.size()); 1089 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 1090 for (unsigned I = 0, N = TyIds.size(); I != N; ++I) 1091 FilterIds.push_back(TyIds[I]); 1092 FilterEnds.push_back(FilterIds.size()); 1093 FilterIds.push_back(0); // terminator 1094 return FilterID; 1095 } 1096 1097 /// getPersonality - Return the personality function for the current function. 1098 Function *MachineModuleInfo::getPersonality() const { 1099 // FIXME: Until PR1414 will be fixed, we're using 1 personality function per 1100 // function 1101 return !LandingPads.empty() ? LandingPads[0].Personality : NULL; 1102 } 1103 1104 /// getPersonalityIndex - Return unique index for current personality 1105 /// function. NULL personality function should always get zero index. 1106 unsigned MachineModuleInfo::getPersonalityIndex() const { 1107 const Function* Personality = NULL; 1108 1109 // Scan landing pads. If there is at least one non-NULL personality - use it. 1110 for (unsigned i = 0; i != LandingPads.size(); ++i) 1111 if (LandingPads[i].Personality) { 1112 Personality = LandingPads[i].Personality; 1113 break; 1114 } 1115 1116 for (unsigned i = 0; i < Personalities.size(); ++i) { 1117 if (Personalities[i] == Personality) 1118 return i; 1119 } 1120 1121 // This should never happen 1122 assert(0 && "Personality function should be set!"); 1123 return 0; 1124 } 1125 1126 //===----------------------------------------------------------------------===// 1127 /// DebugLabelFolding pass - This pass prunes out redundant labels. This allows 1128 /// a info consumer to determine if the range of two labels is empty, by seeing 1129 /// if the labels map to the same reduced label. 1130 1131 namespace llvm { 1132 1133 struct DebugLabelFolder : public MachineFunctionPass { 1134 static char ID; 1135 DebugLabelFolder() : MachineFunctionPass((intptr_t)&ID) {} 1136 1137 virtual bool runOnMachineFunction(MachineFunction &MF); 1138 virtual const char *getPassName() const { return "Label Folder"; } 1139 }; 1140 1141 char DebugLabelFolder::ID = 0; 1142 1143 bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) { 1144 // Get machine module info. 1145 MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>(); 1146 if (!MMI) return false; 1147 1148 // Track if change is made. 1149 bool MadeChange = false; 1150 // No prior label to begin. 1151 unsigned PriorLabel = 0; 1152 1153 // Iterate through basic blocks. 1154 for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); 1155 BB != E; ++BB) { 1156 // Iterate through instructions. 1157 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { 1158 // Is it a label. 1159 if (I->isDebugLabel()) { 1160 // The label ID # is always operand #0, an immediate. 1161 unsigned NextLabel = I->getOperand(0).getImm(); 1162 1163 // If there was an immediate prior label. 1164 if (PriorLabel) { 1165 // Remap the current label to prior label. 1166 MMI->RemapLabel(NextLabel, PriorLabel); 1167 // Delete the current label. 1168 I = BB->erase(I); 1169 // Indicate a change has been made. 1170 MadeChange = true; 1171 continue; 1172 } else { 1173 // Start a new round. 1174 PriorLabel = NextLabel; 1175 } 1176 } else { 1177 // No consecutive labels. 1178 PriorLabel = 0; 1179 } 1180 1181 ++I; 1182 } 1183 } 1184 1185 return MadeChange; 1186 } 1187 1188 FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); } 1189 1190 } 1191